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
Step 2: Implementing InvocationHandler
This class will excute invoke method when the instance of MyInterface call doSomeThing()
Step 3: Create new MyInvocationHandler and test
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
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
Post a Comment