1

In a library, there is a function takes a Class object as parameter:

public void libMethod(Class<?> cls){...}

I need to invoke this library function in Java Reflection way.

For example I have a class :

public MySchool extends School{...}

I want to pass MySchool class to the library function. I tried:

//I can successfully get library class & a instance of it
Class<?> libClass = GET_LIB_CLASS();

//How can I define the type for the parameter?
Method m = libClass.getDeclaredMethod("libMethod", new Class[]{MySchool.class});
return m.invoke(libClass.newInstance(), MySchool.class);

I tried in above way, but it doesn't work.

How can I define the type for the parameter in my above java reflection way ?

1 Answer 1

1

Note that your method takes argument of type Class<?>. The argument you pass to the Class#getDeclaredMethod() is an array of Class instances for the format parameter types of that method, which in this case will be Class.class, and not MySchool.class.

So, you should get the method as:

Method m = libClass.getDeclaredMethod("libMethod", new Class[]{Class.class});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.