在return 后面直接添加invoke方法,外部不用强转直接可以获取调用方法返回值。
- package com.heima;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.ArrayList;
- import java.util.List;
- public class Test6 {
- public static void main(String[] args) throws Exception {
- ArrayList<String> aList = new ArrayList<>();
- MInvocationHandler h = new MInvocationHandler(aList);
- List<String> list = (List) Proxy.newProxyInstance(aList.getClass().getClassLoader(),
- aList.getClass().getInterfaces(), h);
- Boolean b=list.add("Hello");
- Integer size=list.size();
- String s=list.get(0);
- System.out.println(b);
- System.out.println(size);
- System.out.println(s.length());
-
- }
- }
- class MInvocationHandler implements InvocationHandler {
- private Object target;
- public MInvocationHandler(Object target) {
- this.target = target;
- }
- public Object invoke(Object obj, Method m, Object[] args) throws Throwable {
- System.out.println("检查完毕!");
-
- return m.invoke(target, args);
- }
- }
复制代码
|