JDK Dynamic Proxies - Dynamically implement an Interface

The new concept JDK Dynamic Proxies



https://www.logicbig.com/tutorials/core-java-tutorial/java-dynamic-proxies.html



Step 1: Creating an Interface

 private static interface MyInterface {

        void doSomething ();

  }


Step 2: Implementing InvocationHandler

public class MyInvocationHandler implements InvocationHandler {



    @Override

    public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("Hello Dynamically implement an Interface");

        return null;

    }

}


This class will excute invoke method when the instance of MyInterface call doSomeThing()



Step 3: Create new MyInvocationHandler and test

// create new handler object

MyInvocationHandler handler = new MyInvocationHandler();



// create  new instance of MyInterface by Proxy

MyInterface o = (MyInterface) Proxy.newProxyInstance(

                            MyInvocationHandler.class.getClassLoader(),  // Loader

                            new Class[]{MyInterface.class},  // new instance of MyInterface

                            handler  // handler to call invoke method above

                            );



//test

o.doSomething();  // it will do what implementing in the invoke method above  which 
// print  "Hello Dynamically implement an Interface"



End: In this example, we demonstrated how to implement an interface during runtime and what we can achieve by doing that.

and we can think about why JPA work, and AOP in Spring work 

Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch