JDK自带的Proxy动态代理两种实现方式
前提条件:JDK Proxy必须实现对象接口
so,创建一个接口文件,一个实现接口对象,一个动态代理文件
接口文件:TargetInterface.java
package proxy; public interface TargetInterface {
public String method1();
public void method2();
public int method3(int x);
}
实现接口对象的Class文件:Target.java
package proxy; public class Target implements TargetInterface{ @Override
public String method1() {
// TODO Auto-generated method stub
System.out.println("method1 running...");
return "aaa";
} @Override
public void method2() {
// TODO Auto-generated method stub
System.out.println("method2 running...");
} @Override
public int method3(int x) {
// TODO Auto-generated method stub
return x;
} }
动态代理的两种实现方式
1.ProxyTest.java
package proxy; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import org.junit.Test; public class ProxyTest {
@Test
public void test1() {
TargetInterface newProxyInstance = (TargetInterface) Proxy.newProxyInstance(
Target.class.getClassLoader(),
new Class[] {TargetInterface.class},
new InvocationHandler() {
//invoke 代表的是执行代理对象的方法
@Override
//method:代表目标对象的方法字节码对象
//args:代表目标对象的响应的方法的参数
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object invoke = method.invoke(new Target(), args);
return invoke;
}
}); String method1 = newProxyInstance.method1();
newProxyInstance.method2();
int method3 = newProxyInstance.method3(100);
System.out.println(method1);
System.out.println(method3);
}
}
2.ProxyTest2.java
package proxy; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import org.junit.Test; public class ProxyTest2 { public static void main(String[] args) {
Target target = new Target();
TargetInterface newProxyInstance = (TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//反射知识点
Object invoke = method.invoke(target, args);
return invoke;
}
});
String method1 = newProxyInstance.method1();
newProxyInstance.method2();
int method3 = newProxyInstance.method3(100);
System.out.println(method1);
System.out.println(method3);
} }
运行结果都如下所示:
总结下重要的就是:
1.熟练Proxy.newProxyInstance的使用
2.JDK的Proxy一定要实现接口。