jdk动态代理 类型问题
来源:9-7 SpringAOP的实现之CGLIB动态代理-
代夫阿普曼
2020-06-13
翔仔老师好,我在jdk动态代理卡住了。在运行测试类ProxyDemo里报错一个错误:
错误提示我,需要泛型T,代码中不是已经强转成T了嘛,这是什么原因呢。jdk动态代理的工具类是这样的:
public class JdkDynamicProxyUtils {
public static <T>T newProxyInstance(T targetObject, InvocationHandler handler){
ClassLoader classLoader = targetObject.getClass().getClassLoader();
Class<?>[] interfaces = targetObject.getClass().getInterfaces();
return (T)Proxy.newProxyInstance(classLoader, interfaces, handler);
}
}
AlipayInvocationHandler类:
public class AlipayInvocationHandler implements InvocationHandler {
private Object targetObject;
public AlipayInvocationHandler(Object targetObject) {
this.targetObject = targetObject;
}
@Override
public Object invoke(Object o, Method method, Object[] args) throws Throwable {
beforePay();
Object result = method.invoke(targetObject, args);
afterPay();
return result;
}
private void beforePay() {
System.out.println("从招行取款");
}
private void afterPay() {
System.out.println("支付给imooc");
}
}
测试类:
public class ProxyDemo {
public static void main(String[] args) {
ToBPaymentImpl toBPayment = new ToBPaymentImpl();
AlipayInvocationHandler alipayInvocationHandler = new AlipayInvocationHandler(toBPayment);
ToBPayment toBPaymentProxy = JdkDynamicProxyUtils.newProxyInstance(toBPayment, alipayInvocationHandler);
toBPaymentProxy.pay();
}
}
这是啥问题呢,麻烦老师看一下?
写回答
1回答
-
代夫阿普曼
提问者
2020-06-13
这是放在gradle那边运行时报错,在maven这边是对的
00
相似问题
关于JDK动态代理的问题
回答 1
代理类的处理呢?
回答 1