出现这种情况提示也比较明确 就是传入参数中的ClassLoader并没有找到 传入参数的类 附上报错的代码
public class JdkProxyUtil {
public static<T> T getProxy(Class<T> clazz, final ICacheAdapter adapter) {
System.out.println(clazz.getClass().getClassLoader()); //输出为null 这是BootStrapClassLoader加载的
System.out.println(clazz.getClass().getName()); //输出java.lang.Class
return (T)Proxy.newProxyInstance(clazz.getClass().getClassLoader(), new Class[]{clazz.getInterfaces()[0]}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable,RuntimeException {
String name = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
Method declaredMethod = adapter.getClass().getDeclaredMethod(name, parameterTypes);
if (declaredMethod == null) {
throw new RuntimeException("适配器中找不到适配的方法");
}
return declaredMethod.invoke(adapter, args);
}
});
}
}
错误原因就是newProxyInstance方法中的第一个参数多了一个.getClass() 手快了 以为传进来的是一个相应的类的Object对象
这样获取的就是java.lang.Class的类加载器 也就是BootStrapClassLoader 而明显我们项目中的的class文件的加载器是AppClassLoader 所以BootStrapClassLoader不能获取到相应的接口的类 报错interface ** is not visible from class loader