Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 : Invoke Interface's static method using reflection

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.

like image 687
Ankush soni Avatar asked Jul 30 '15 08:07

Ankush soni


People also ask

How do you call a static method using reflection?

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.

How do we invoke static methods?

We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.

How do you call a static method from another class in Java?

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.

How do you create an instance of a class using 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

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);
like image 105
Tagir Valeev Avatar answered Nov 11 '22 23:11

Tagir Valeev