jeudi 5 octobre 2017

Calling non-static methods of a class through reflection in java

How to call the non-static methods of built-in classes like java.util.ArrayList, java.util.Integer, etc. through reflection.

I can call the the static methods of the class from the following segment of code:

Class temp = Class.forName(className); // className is the name of the class.
Method method = temp.getMethod(className, classtypes); // classtypes is a Class type array which contains the types of each argument
method.invoke(null,arguments); // arguments is an object type array which contains the arguments (values)

But when I call the method.invoke(temp,arguments) it gives me java.lang.NoSuchMethodException.

Note: Since the class may not have default constructor (empty constructor), so I cannot call the non-static method by using className.getInstance() either.

There are of course similar questions available, but they do not solve my problem





Aucun commentaire:

Enregistrer un commentaire