Java: reflection for calling methods in a non-public class that implements an open interface

I am trying to use reflection to call a method whose name and arguments are known at runtime, and I fail with an IllegalAccessException .

This is an object that is an instance of a non-public class that implements an open interface, and I have a brain spasm trying to remember the correct way to call such a method.

 public interface Foo { public int getFooValue(); } class FooImpl implements Foo { @Override public int getFooValue() { return 42; } } Object foo = new FooImpl(); 

Given the foo object, how would I call foo.getFooValue () reflexively?

If I look at the results of foo.getClass().getMethods() , this should work, but I think it raises an IllegalAccessException . Is this the case when I need to call getDeclaredMethods() ? Or do I need to go through public interfaces / superclasses and call getDeclaredMethods there?

+4
source share
2 answers

It works:

 import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Ex { public static void main(String[] args) throws Exception { final String methodName = "getFooValue"; Object foo = new FooImpl(); Class<?> c = foo.getClass(); Method m = c.getDeclaredMethod(methodName, null); System.out.println(m.invoke(foo)); } } interface Foo { public int getFooValue(); } class FooImpl implements Foo { @Override public int getFooValue() { return 49; } } 
+3
source

I think you should call getDeclaredMethods ().

Here is an example:

 Method methods[] = secretClass.getDeclaredMethods(); System.out.println("Access all the methods"); for (int i = 0; i < methods.length; i++) { System.out.println("Method Name: " + methods[i].getName()); System.out.println("Return type: " + methods[i].getReturnType()); methods[i].setAccessible(true); System.out.println(methods[i].invoke(instance, EMPTY) + "\n"); } 

By the way, a message with a link to the reflection of private classes :

When it comes to bytecode (i.e. runtime), there is no such thing as a private class. This is a fiction supported by the compiler. The reflection API has a type available to the package with a public member method.

0
source

All Articles