不适用spring但又需要写入一些方法的日子应该咋办?
这就需要动态代理实现。
思路:
创建一个类A
类A中包含要代理类的私有属性。
通过get方法获取该类的代理。proxy=(Arthmetic)Proxy.newProxyInstance(loader, interfaces, h);
在get方法中使用Proxy 代码如下:
package com.nan.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.nan.info.Arthmetic;
public class ArthemeticProxy {
private Arthmetic target;
public ArthemeticProxy() {}
public ArthemeticProxy(Arthmetic target) {
this.target=target;
}
public Arthmetic getArthmeticProxy() {
Arthmetic proxy=null;
// 获取类加载器
ClassLoader loader=target.getClass().getClassLoader();
Class[]interfaces =new Class[] {Arthmetic.class};
InvocationHandler h=new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName());
System.out.println(args[0]);
return 0;
}
};
proxy=(Arthmetic)Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}