https://www.zhihu.com/question/20794107
public class Main {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//People为接口
//代理的对象User实现接口People
//获得代理Class对象
Class peopleProxyClass = Proxy.getProxyClass(People.class.getClassLoader(),People.class);
//获得代理Class对象的构造器
Constructor constructor = peopleProxyClass.getConstructor(InvocationHandler.class);
//通过构造器获得代理对象
People peopleImpl = (People)constructor.newInstance(new InvocationHandler() {
//实现代理
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法前的业务
System.out.println("方法执行前");
//user为代理对象
User user = new User();
//执行代理对象的原方法
//通过InvocationHandler的实例调用
Object result = method.invoke(user,args);
//方法后的业务
System.out.println("方法执行后");
return result;
}
});
//执行代理对象的方法
peopleImpl.print();
User user = new User();
People people = (People) getProxy(user);
people.print();
}
private static Object getProxy(final Object target) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class peopleProxyClass = Proxy.getProxyClass(target.getClass().getClassLoader(),target.getClass().getInterfaces());
Constructor constructor = peopleProxyClass.getConstructor(InvocationHandler.class);
Object proxy = constructor.newInstance(new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法前的业务
System.out.println("方法执行前");
//target为代理对象
Object result = method.invoke(target,args);
//方法后的业务
System.out.println("方法执行后");
return result;
}
});
return proxy;
}
private static Object getProxy2(final Object target) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//使用newProxyInstance
Object proxy = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法前的业务
System.out.println("方法执行前");
//target为代理对象
Object result = method.invoke(target,args);
//方法后的业务
System.out.println("方法执行后");
return result;
}
});
return proxy;
}
}