抽象角色
public interface UserService {
void add();
void delete();
void update();
void query();
}
实现了接口的真实角色
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("执行了add方法");
}
public void delete() {
System.out.println("执行了delete方法");
}
public void update() {
System.out.println("执行了update方法");
}
public void query() {
System.out.println("执行了query方法");
}
}
利用InvocationHandler实现动态代理的处理程序
其实这样实现该类,已经可以使用其作为工具类,方便以后实现动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String name){
System.out.println("执行的是真实类实现的接口的"+name+"方法");
}
}
测试
public class MyTest {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
运行结果
还不熟悉。需要进一步的理解。