Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java reflection call methods of an already loaded object

How can I call the method of an object that has already been loaded in the JVM using reflection? I tried

Class myClass = Class.forName("myClass");
Method m = com.test.class.getDeclaredMethod("getValue",new Class[] {});
Object result = m.invoke(myClass,null);

but i get java.lang.IllegalArgumentException: object is not an instance of declaring class. The method I want to call is void i.e. does not take parameters

UPDATE I have an application that has already loaded a class "A". Another class "B" will be instantiated by a framework. When class "B" is initialized, class "A" has already been loaded in the JVM. I want to call a method from loaded instance of class "A" BUT without having a reference to "A" in class "B". In the answers, it seems I must create a new instance of "A" in class "B" but I want access to an already loaded object. If I create a new instance of "A" in "B" why would I want to use reflection? Am I missunderstanding something?

Thanks

like image 813
Cratylus Avatar asked Sep 10 '10 21:09

Cratylus


People also ask

How do you call a method from an object in Java?

The dot ( . ) is used to access the object's attributes and methods. To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main.java).

Is Java Reflection slow or expensive?

Adding setAccessible(true) call makes these reflection calls faster, but even then it takes 5.5 nanoseconds per call. Reflection is 104% slower than direct access (so about twice as slow).

How do you instantiate an object using a reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.


1 Answers

You're passing the instance of Class as the first parameter to Method.invoke(..), but that's wrong; you want to pass the instance you're interested in.

result = m.invoke(myInstance, null);
like image 176
Ladlestein Avatar answered Oct 13 '22 02:10

Ladlestein