自定義靜態代理:相對於動態代理不靈活。
反射動態代理: 相比較靜態代理要靈活,自己實現反射。
JDK動態代理:基於反射實現,目標對象必須要有接口。生成的代理類是接口的一個實現類。
CGLib動態代理:CGLib底層採用ASM字節碼生成框架,使用字節碼技術生成代理類,比使用Java反射效率要高,比JDK動態代理效率稍低,但目標對象不需要有接口。生成的代理類是目標類的子類,因此目標類不能是final的。CGLib動態代理
自定義靜態代理:接口類
public interface Hello {
public String hello(String hello);
}
自定義靜態代理:接口實現類
public class HelloImpl implements Hello{
public String hello(String hello) {
System.out.println("自定義靜態代理--》\t"+hello);
return hello;
}
}
自定義靜態代理:代理類
public class HelloProxy{
private HelloImpl impl;
public HelloProxy(HelloImpl impl){
this.impl=impl;
}
public void hello(String str){
impl.hello(str);
}
}
自定義靜態代理:測試類
public class Test {
public static void main(String[] args) {
HelloProxy hander=new HelloProxy(new HelloImpl());
hander.hello("123456");
}
}
反射動態代理:接口類
public interface Hello {
public String hello(String hello);
}
反射動態代理:接口實現類
public class HelloImpl implements Hello{
public String hello(String hello) {
System.out.println("反射動態代理--》\t"+hello);
return hello;
}
}
反射動態代理:代理類
public class ProxyHander implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(proxy, args);
}
}
反射動態代理:測試類
public class Test {
public static void main(String[] args) throw Exception{
ProxyHander hander=new ProxyHander();
hander.invoke(new HelloImpl(), Hello.class.getMethod("hello",String.class), new String[] {"123456"});
}
}
JDK動態代理:接口類
public interface Hello {
public String hello(String hello);
}
JDK動態代理:接口類實現類
public class HelloImpl implements Hello{
public String hello(String hello) {
System.out.println("JDK動態代理--》\t"+hello);
return hello;
}
}
JDK動態代理:JDK動態代理處理類
public class ProxyHander implements InvocationHandler {
private Object target;
public Object createProxyObject(Object target) {
this.target=target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target, args);
}
}
JDK動態代理:JDK動態代理測試類
public class Test {
public static void main(String[] args) {
ProxyHander hander=new ProxyHander();
Hello hello=(Hello) hander.createProxyObject(new HelloImpl());
hello.hello("123456");
}
}