参数说明
Object obj = Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object object = method.invoke(new Person(), args);
return object;
}
});
loader:需要代理接口的类加载器
interfaces:实现功能的类所实现的接口类。new Class[]{} ()
new InvocationHandler匿名对象,实现接口中的方法。
invoke中的参数说明:
proxy:代理对象
method:所调用的方法。
args:方法的参数
object:方法的返回值
案例:
需要代理的接口
public interface Daily {
void run();
int eat();
}
public interface Play {
void playGame();
void playBall();
}
Person类(实现接口)
public class Person implements Play,Daily{
@Override
public void run() {
System.out.println("run");
}
@Override
public int eat() {
System.out.println("eat");
return 0;
}
@Override
public void playGame() {
System.out.println("playGame");
}
@Override
public void playBall() {
System.out.println("playBall");
}
}
测试类
((Daily) Proxy.newProxyInstance(Daily.class.getClassLoader(), new Class[] { Play.class, Daily.class },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法开始前的工作");
Object object = method.invoke(new Person(), args);
System.out.println("方法执行结束");
return object;
}
})).eat();
((Daily)Proxy.newProxyInstance(Daily.class.getClassLoader(), new Class[] { Play.class, Daily.class },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// System.out.println(proxy.getClass());
System.out.println("方法开始前的工作");
Object object = method.invoke(new Person(), args);
System.out.println("方法执行结束");
return object;
}
})).run() ;
((Play) Proxy.newProxyInstance(Play.class.getClassLoader(), new Class[] { Play.class, Daily.class },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法开始前的工作");
Object object = method.invoke(new Person(), args);
System.out.println("方法执行结束");
return object;
}
})).playBall();
((Play) Proxy.newProxyInstance(Play.class.getClassLoader(), new Class[] { Play.class, Daily.class },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法开始前的工作");
Object object = method.invoke(new Person(), args);
System.out.println("方法执行结束");
return object;
}
})).playGame();
}
打印结果:
方法开始前的工作
eat
方法执行结束
方法开始前的工作
run
方法执行结束
方法开始前的工作
playBall
方法执行结束
方法开始前的工作
playGame
方法执行结束