Search code examples
javamethodsjava-8default

How to explicitly invoke default method simply, without reflection and dynamic Proxy?


I was reading about default methods in Java 8 and I got stuck in one thing - is there a way to invoke default method from interface without implementing it, or using dynamic Proxy? By using just a simple way, like in following methods:

interface DefaultTestInterface{
    default void method1(){
        //default method
    }
}
class ImplementingClass implements DefaultTestInterface{
    public void method1(){
        //default method invocation in implementing method
        DefaultTestInterface.super.method1();
    }
    void method2(){
        //default method invocation in implementing class
        DefaultTestInterface.super.method1();
    }
}
public class Main {
    public static void main(String[] args) {
        //is there any way to simply invoke default method without using proxy and reflection?
    }
}

I read similar questions, but the first was connected only with invocation in implementing method, and two others was connected with dynamic Proxy using reflection and reflection.

Those solutions are quite complicated and I am wondering if there is simpler way of doing it. I also read those articles, but I didn't found solution for my problem. I would be grateful for any help.


Solution

  • If the interface has only one method, or all its methods have default implementations, all you need to do is creating an anonymous implementation that does not implement the method that you wish to call:

    (new DefaultTestInterface() {}).method1();
    

    Demo.