java 动态代理,
分享于 点击 18674 次 点评:71
java 动态代理,
动态代理就是通过反射来生成一个代理
在java中java.lang.reflect包下提供了一个Proxy类和一个InvocationHandler接口,通过这个类和接口就可以生成动态代理对象.JDK提供的代理只能针对接口做代理.我们有更强大的代理cglib,Proxy类中的方法创建动态代理对象
Student.java
public interface Student {
public void login();
public void submit();
}
StudentImp.java
public class StudentImp implements Student {
@Override
public void login() {
System.out.println("登录");
}
@Override
public void submit() {
System.out.println("提交");
}
}
User.java
public interface User {
public void add();
public void delete();
}
UserImp.java
public class UserImp implements User {
@Override
public void add() {
//System.out.println("权限校验");
System.out.println("添加功能");
//System.out.println("日志记录");
}
@Override
public void delete() {
//System.out.println("权限校验");
System.out.println("删除功能");
//System.out.println("日志记录");
}
}
MyInvocationHandler.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("权限校验");
method.invoke(target, args); //执行被代理target对象的方法
System.out.println("日志记录");
return null;
}
}
Test.java
import java.lang.reflect.Proxy;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
/*UserImp ui = new UserImp();
ui.add();
ui.delete();
System.out.println("-------------------------------");*/
/*
* public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,
* InvocationHandler h)
*/
/*MyInvocationHandler m = new MyInvocationHandler(ui);
User u = (User)Proxy.newProxyInstance(ui.getClass().getClassLoader(), ui.getClass().getInterfaces(), m);
u.add();
u.delete();*/
StudentImp si = new StudentImp();
si.login();
si.submit();
System.out.println("-------------------------------");
MyInvocationHandler m = new MyInvocationHandler(si);
Student s = (Student)Proxy.newProxyInstance(si.getClass().getClassLoader(), si.getClass().getInterfaces(), m);
s.login();
s.submit();
}
}
相关文章
- 暂无相关文章
用户点评