在练习jdk动态代理时遇到 java.lang.IllegalArgumentException: object is not an instance of declaring class;
原因是未能获取实例,使用method.invoke(bean.getClass().newInstance(),args);
Object newProxyInstance =
Proxy.newProxyInstance(
ZhangyuBeanPostProcessor.class.getClassLoader(),
bean.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理对象"+bean);
//错误信息:object is not an instance of declaring class
//
//说明Class没有实例化;
//解决办法:
//由于没有实力化可以有如下两种方法:
//1、反射方法定义成为static的,故被反射类就不需要实例化;
//2、method.invoke(class.newInstance(), args);
return method.invoke(bean.getClass().newInstance(),args);
//错误语句
// return method.invoke(bean.getClass(),args);
}
});