reflection
Create Proxy object
With this example we are going to demonstrate how to create a Proxy object. A proxy is a class functioning as an interface to a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, to create a Proxy object we have followed the steps below:
- We have created an interface,
MyInterface
with a method and the implementation of the interface,MyInterfaceImpl
. - We have created
MyProxy
class,that implements the InvocationHandler. It has an Object o and a constructor where it initializes its object. It also has a method,Object invoke(Object proxy, Method m, Object[] args)
, that usesinvoke(Object obj, Object... args)
API method of Method to get the underlying method represented by this Method object, on the specified object with the specified parameters and returns this result. - We create an instance of a proxy class for the specified interface that dispatches method invocations to the specified invocation handler, using
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
API method of Proxy. - Then we invoke the method of the object.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class CreateProxyObject { public static void main(String[] args) { // return an instance of a proxy class for the specified interfaces // that dispatches method invocations to the specified invocation handler MyInterface myintf = (MyInterface)Proxy.newProxyInstance( MyInterface.class.getClassLoader(), new Class[]{MyInterface.class}, new MyProxy(new MyInterfaceImpl()) ); // Invoke the method myintf.method(); } private static interface MyInterface { void method(); } private static class MyInterfaceImpl implements MyInterface { public void method() { System.out.println("Plain method is invoked"); } } private static class MyProxy implements InvocationHandler { Object obj; public MyProxy(Object o) { obj = o; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object result = null; try { System.out.println("Proxy Class is called before method invocation"); result = m.invoke(obj, args); } catch (InvocationTargetException e) { System.out.println("Invocation Target Exception: " + e); } catch (Exception e) { System.out.println("Invocation Target Exception: " + e); } finally { System.out.println("Proxy Class is called after method invocation"); } return result; } } }
Output:
Proxy Class is called before method invocation
Plain method is invoked
Proxy Class is called after method invocation
This was an example of how to create a Proxy object in Java.