I want to invoke static method of Java 8 interface using reflection API.
public interface TimeClient {
static void testStatic() {
System.out.println("In the Static");
}
}
I am able to invoke default method of Interface but unable to invoke static method.
In the example above, we first obtain the instance of the class we want to test, which is GreetingAndBye. After we have the class instance, we can get the public static method object by calling the getMethod method. Once we hold the method object, we can invoke it simply by calling the invoke method.
We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.
Call a static Method in Another Class in Java In the case of a static method, we don't need to create an object to call the method. We can call the static method by using the class name as we did in this example to call the getName() static method.
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.
I see no problems:
TimeClient.class.getDeclaredMethod("testStatic").invoke(null);
Works without problems and prints "In the Static". The getMethod
also works as expected:
TimeClient.class.getMethod("testStatic").invoke(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