JDK:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxyTest {
public static Object createProxy(Object object){
//jdk的动态代理方法
//可用于日志管理,动态代理等
ClassLoader classLoader = object.getClass().getClassLoader();
Class<?>[] interfaces = object.getClass().getInterfaces();
return Proxy.newProxyInstance(classLoader, interfaces, (Object proxy, Method method, Object[] args) ->{
Class<?>[] interfaces1 = proxy.getClass().getInterfaces();
Field[] fields = interfaces[0].getFields();
String methodName = method.getName();
System.out.println("正在执行"+methodName+"方法");
return method.invoke(object, args);
});
}
static interface User{
public void setName(String name);
public String getName();
}
static class UserImpl implements User {
String name;
String phone;
int age;
public UserImpl(String userName){
this.name = userName;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
public static void main(String[] args) {
User user = (User)createProxy(new UserImpl("张三"));
user.setName("李四");
String name = user.getName();
System.out.println(name);
}
}
cglib:
import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class CglibProxyTest { public static Object createProxy(Object object){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(object.getClass()); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { System.out.println("正在执行"+method.getName()+"方法"); return method.invoke(object, args); } }); return enhancer.create(); } public static void main(String[] args) { Usern user = new Usern("wanger"); Usern userimpl = (Usern) createProxy(user); String name = userimpl.getName(); System.out.println(name); } static class Usern{ String name; int age; public Usern(){ } public Usern(String name){ this.name = name; } public String getName(){ return name; } } }