运行环境java18
为什么会报错:
public Object intercept(Invocation invocation)这里拿到的是个代理对象。里面还套着几层就拿不到东西。
解决方案:
网上提供的解决方案大多数是针对于java8的,也就是
private static <T>T realTarget(Object target) { if (Proxy.isProxyClass(target.getClass())) { MetaObject metaObject = SystemMetaObject.forObject(target); return realTarget(metaObject.getValue("h.target")); } return (T) target; }
这样,然后把invocation.getTarget()传进来,获取实际对象。
但是在java9之后的版本,反射修改了一点,这里会报错,不允许访问h对象。
Unable to make field protected java.lang.reflect.InvocationHandler java.lang.reflect.Proxy.h accessible: module java.base does not "opens java.lang.reflect" to unnamed module
这里的解决方案是
干脆不自己写realTarget。引入com.baomidou.mybatisplus.core.toolkit.PluginUtils并使用mybatisplus提供的PluginUtils.realTarget。
直接StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
然后就搞定了