java动态代理demo
作者:互联网
首先一个接口
public interface MyInterface {
void method1(String arg);
}
再写一个接口实现类
public class MyInterfaceImpl implements MyInterface {
/*
* (non-Javadoc)
* @see reflectStudy.MyInterface#method1()
*/
@Override
public void method1(String arg) {
System.out.println("MyInterfaceImpl:arg=" + arg);
}
}
然后就是代理类,
动态代理: 如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。
public class MyInvocationHandler implements InvocationHandler {
private Object obj = null;
public Object getNewInstance(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(this.obj, args);
}
}
client测试
/**
*
*
* @throws Throwable
* @throws SecurityException
*/
private static void invocationHandler2() throws SecurityException, Throwable {
MyInvocationHandler demo = new MyInvocationHandler();
MyInterface impl = (MyInterface) demo.getNewInstance(new MyInterfaceImpl());
String arg = "hello";
Object[] objs = new Object[] { arg };
demo.invoke(impl, MyInterface.class.getMethods()[0], objs);
impl.method1("helllo");
}
run result:
MyInterfaceImpl:arg=hello
MyInterfaceImpl:arg=helllo
标签:obj,demo,Object,代理,MyInterface,arg,java,public,MyInterfaceImpl 来源: https://blog.51cto.com/10983206/2564136