mercredi 10 mai 2023

How to pass parameter to invoke method as a vararg of a relfected class in case of Java reflection?

I have a project in which I am using a third party library. However, I need to call methods from the third party only if the user has copied those jars in the project, or else use the existing jars. For this purpose I am using reflection for creating the classes and calling the methods from this third party library.

One of the methods from the library expects varargs of another class from the same library as argument. Since both the classes have been created in my main class using reflection and also their corresponding methods have been created using reflection, how do we pass argument as vararg of a class to the methodname.invoke() method?

Refer the code snippet ahead.

//-------Class A-----------------

package com.demoA;

Class A {
   public void methodA(B... b) {
      // Contents of methodA...
   }
}

//-------Class B-----------------

package com.demoB;

Class B {
    // contents of class B here...
}

//-------Class MainClass-------------

package com.mainclass;

Class MainClass {
    public static void main(String[] args) {
        Class<?> azz = Class.forName("com.demoA.A");
        Object aObject = azz.getDeclaredConstructor().newInstance();
        Method methodAReflected = null;
    
        for (Method m : azz.getMethods) {
            if (m.getName.equals("methodA")) {
                methodAReflected = m;
            }
        }
        
          Class bzz = Class.forName("com.demoB.B");
          Object bObject = bzz.getDeclaredConstructor().newInstance();
        
          methodAReflected.invoke(aObject, <how to pass varargs here>);
          // Passing only bObject or new Object[] { bObject } result in an IllegalArgumentException : type mismatch
    
    }
}

Also, is there is any better way (rather than iterating through the method names) to use Java reflection's getMethod() method to create the reflected method when the expected parameter is a vararg?





Aucun commentaire:

Enregistrer un commentaire