jdk实现动态代理
Class[] c = {Add.class};
// Book.class.getClassLoader()类加载器 c 存放的是一个接口类的类数组 new UserProxy实现了InvocationHandler接口
Add o = (Add)Proxy.newProxyInstance(Book.class.getClassLoader(), c, new UserProxy(new AddImpl()));
// 转换类型 调用接口的方法
o.add();
o.show(2,3);
}
}
class UserProxy implements InvocationHandler {
private Object obj;
public UserProxy(Object obj){
this.obj=obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke=null;
// if(method.getName().equalsIgnoreCase("show")){
// method.getName()方法的名字 args方法的参数
// System.out.println(method.getName()+"==="+ Arrays.toString(args));
// invoke = method.invoke(obj, args);
// }
// 方法返回的参数
invoke = method.invoke(obj,args);
System.out.println("in"+invoke);
return invoke;
}
}



举报 0