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
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).
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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With