the*_*kid 14 java reflection interface java-8
鉴于这个简单的"Hello World"是Java 8接口,如何通过反射调用其hello()方法?
public interface Hello {
default String hello() {
return "Hello";
}
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*ont 15
您可以使用MethodHandles:
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ReflectiveDefaultMethodCallExample {
static interface Hello {
default String hello() {
return "Hello";
}
}
public static void main(String[] args) throws Throwable{
Hello target =
//new Hello(){};
(Hello)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{Hello.class}, (Object proxy, Method method, Object[] arguments) -> null);
Method method = Hello.class.getMethod("hello");
Object result = MethodHandles.lookup()
.in(method.getDeclaringClass())
.unreflectSpecial(method,method.getDeclaringClass())
.bindTo(target)
.invokeWithArguments();
System.out.println(result); //Hello
}
}
Run Code Online (Sandbox Code Playgroud)
Luk*_*der 13
不幸的是,似乎没有一个理想的解决方案适用于所有JDK 8,9,10,它们的行为不同.在jOOR修复问题时遇到了问题.我还在这里详细介绍了正确的解决方案.
在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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是唯一适用于私有访问和私有不可访问接口的方法.但是,上述方法对JDK内部进行非法反射访问,这将在将来的JDK版本中不再起作用,或者--illegal-access=deny
在JVM上指定.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
只需实现上述两种解决方案,并检查您的代码是在JDK 8上运行还是在以后的JDK上运行,您就可以了.直到你不是:)
非常感谢卢卡斯。这是他对 Java 8 与 9+ 检查以及对非 void 返回和参数的支持的回答。一定要给他的回答点赞。
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
public class ThanksLukas implements InvocationHandler {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (method.isDefault()) {
final float version = Float.parseFloat(System.getProperty("java.class.version"));
if (version <= 52) {
final Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class);
constructor.setAccessible(true);
final Class<?> clazz = method.getDeclaringClass();
return constructor.newInstance(clazz)
.in(clazz)
.unreflectSpecial(method, clazz)
.bindTo(proxy)
.invokeWithArguments(args);
} else {
return MethodHandles.lookup()
.findSpecial(
method.getDeclaringClass(),
method.getName(),
MethodType.methodType(method.getReturnType(), new Class[0]),
method.getDeclaringClass()
).bindTo(proxy)
.invokeWithArguments(args);
}
}
// your regular proxy fun here
Run Code Online (Sandbox Code Playgroud)
您无法直接调用它,因为您需要实现类的实例.为此,您需要一个实现类.default
method不是static
方法,也不能创建接口的实例.
所以,假设你有一个实现类:
class HelloImpl implements Hello { }
Run Code Online (Sandbox Code Playgroud)
您可以像这样调用方法:
Class<HelloImpl> clazz = HelloImpl.class;
Method method = clazz.getMethod("hello");
System.out.println(method.invoke(new HelloImpl())); // Prints "Hello"
Run Code Online (Sandbox Code Playgroud)
我找到了一种解决方案sun.misc.ProxyGenerator
,可以通过反射性地使用通过组装字节码来定义类的代码从上述接口创建实例HelloImpl
。现在我可以写:
Class<?> clazz = Class.forName("Hello");
Object instance;
if (clazz.isInterface()) {
instance = new InterfaceInstance(clazz).defineClass().newInstance();
} else {
instance = clazz.newInstance();
}
return clazz.getMethod("hello").invoke(instance);
Run Code Online (Sandbox Code Playgroud)
……但这太难看了。
归档时间: |
|
查看次数: |
5265 次 |
最近记录: |