不幸的是,似乎没有一个理想的解决方案适用于所有表现不同的 JDK 8、9、10。 I've run into issues when fixing an issue in jOOR。 I've also blogged about the correct solution here in detail.
这种方法适用于 Java 8
在 Java 8 中,理想的方法是使用从 Lookup 访问包私有构造函数的 hack:
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;
interface Duck {
default void quack() {
System.out.println("Quack");
}
}
public class ProxyDemo {
public static void main(String[] a) {
Duck duck = (Duck) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[] { Duck.class },
(proxy, method, args) -> {
Constructor<Lookup> constructor = Lookup.class
.getDeclaredConstructor(Class.class);
constructor.setAccessible(true);
constructor.newInstance(Duck.class)
.in(Duck.class)
.unreflectSpecial(method, Duck.class)
.bindTo(proxy)
.invokeWithArguments();
return null;
}
);
duck.quack();
}
}
这是唯一适用于私有可访问和私有不可访问接口的方法。但是,上述方法对 JDK 内部进行了非法反射访问,这在未来的 JDK 版本中将不再有效,或者如果在 JVM 上指定了--illegal-access=deny。
这种方法适用于 Java 9 和 10,但不适用于 8
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Proxy;
interface Duck {
default void quack() {
System.out.println("Quack");
}
}
public class ProxyDemo {
public static void main(String[] a) {
Duck duck = (Duck) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[] { Duck.class },
(proxy, method, args) -> {
MethodHandles.lookup()
.findSpecial(
Duck.class,
"quack",
MethodType.methodType(void.class, new Class[0]),
Duck.class)
.bindTo(proxy)
.invokeWithArguments();
return null;
}
);
duck.quack();
}
}
解决方案
只需实现上述两个解决方案,并检查您的代码是在 JDK 8 还是更高版本的 JDK 上运行,就可以了。直到你不是:)