JDK动态代理
- .利用了JDK API,动态地在内存中构建代理对象,从而实现对目标对象的代理功能。
- .动态代理是在运行时动态生成的,即编译完成后没有实际的class文件,而是在运行时动态生成类字节码,并加载到JVM中
- .不需要实现接口(指的是被代理类的接口),但是要求目标对象必须实现接口,否则不能使用动态代理
- .需要实现InvocationHandler接口,并实现invoke方法,在该方法里面实现增强效果,该方法有三个参数,在下面进行详解
- .代理类调用是通过Proxy的newProxyInstance的方法进行生成
- .使用泛型可以代理多个接口
import lombok.Data;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKTest {
public static void main(String[] args) {
UserHandle userHandle = new UserHandle(new User("xiaoxu",22,"男"));
People people = userHandle.PeopleProxy();
people.run(20.1);
people.eat();
Proxy1<People> peopleProxy1= new Proxy1<>(new User("daxu",23,"男"));
People people1 = peopleProxy1.GetProxy();
people1.run(21.1);
}
}
interface People{
void run(Double velocity);
void eat();
}
@Data
class User implements People{
private String name;
private Integer age;
private String sex;
User(String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public void run(Double velocity){
System.out.println(name+"正以"+velocity+"的速度再跑");
}
@Override
public void eat() {
System.out.println(name+"吃大餐");
}
}
class UserHandle implements InvocationHandler{
private final People people;
UserHandle(People people){
this.people = people;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
start();
Object invoke = method.invoke(people, args);
end();
return invoke;
}
void start(){
System.out.println("-----开始了-------");
}
void end(){
System.out.println("-------结束了-----");
}
People PeopleProxy(){
ClassLoader classLoader = User.class.getClassLoader();
Class<?>[] interfaces = User.class.getInterfaces();
return (People) Proxy.newProxyInstance(classLoader, interfaces,this);
}
}
class Proxy1<T> implements InvocationHandler{
private final T people;
Proxy1(T people){
this.people = people;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
start();
Object invoke = method.invoke(people, args);
end();
return invoke;
}
void start(){
System.out.println("-----开始了-------");
}
void end(){
System.out.println("-------结束了-----");
}
T GetProxy(){
ClassLoader classLoader = User.class.getClassLoader();
Class<?>[] interfaces = User.class.getInterfaces();
return (T) Proxy.newProxyInstance(classLoader, interfaces,this);
}
}
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/abbdf38889a548e7a7ba056ec7c87639.png)