package main;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class App {
public static void main(String[] args) {
System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");
MapperProxy proxy = new MapperProxy();
UserMapper mapper = proxy.newInstance(UserMapper.class);
User user = mapper.getUserById(123, "peter");
User user1 = mapper.getUserById1(222, "peter");
System.out.println(user);
System.out.println(user1);
}
}
class User {
Integer id;
String name;
Integer age;
public User(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
interface UserMapper {
User getUserById(int id, String name);
User getUserById1(int id, String name);
}
class MapperProxy implements InvocationHandler {
// proxy:就是代理对象,newProxyInstance方法的返回对象
//
// method:调用的方法
//
// args: 方法中的参数
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaredAnnotations())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
}
}
Class[] parameterTypes = {String.class, String.class, Integer.class};
Class clazz = method.getReturnType();
Constructor constroctor = clazz.getConstructor(Integer.class, String.class, Integer.class);
// return new User((Integer) args[0], "aaa", 18);
return constroctor.newInstance((Integer) args[0], "aaa", 18);
}
// newProxyInstance,方法有三个参数:
//
// loader: 用哪个类加载器去加载代理对象
//
// interfaces:动态代理类需要实现的接口
//
// h:动态代理方法在执行时,会调用h里面的invoke方法去执行
public <T> T newInstance(Class<T> clz) {
//userMapper接口的invoke//
return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, this);
}
}
jdk动态代理
最新推荐文章于 2024-08-05 07:30:00 发布