InvocationHandler

通过InvocationHandler 来实例化类,可以指定类的类加载器

1 //Application 已经在spring容器中了,构造器注入
//spring 会从容器中找IPrit的实现类,找不到会报错
2 public ApplicationDemo(IPrint printProxy){ 3 4 printProxy.execute(10); 5 6 printProxy.execute(-1); 7 8 }

 

 

1 public interface IPrint extends Ispi<Integer>{
2      default pulbic void execute(int level){
3            doSomething();
4        
5    }
6 
7 }    

 

 1 final InvocationHandler invocationHandler = (proxy, method, args) -> {
    //args是从Ispi对应的方法的入参,即上面的
         default pulbic void execute(int level);
 2     System.out.println("invocationHandler before");
 3     for (Ispi spi : ispiList) {
 4         if (spi.verify(args[0])) {
 5             final Object invoke = method.invoke(spi, args);
 6             System.out.println("invocationHandler after");
 7             return invoke;
 8         }
 9     }
10     return null;
11 };
12 return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{spiClz}, invocationHandler);

 

posted @ 2021-04-30 09:24  龙之谷2019  阅读(75)  评论(0)    收藏  举报