public interface Foo {
int add(int x, int y);
}
public class Bar implements Foo {
int add(int x, int y) {
return x+y;
}
}
现在假设我在 /usr/local
中有 Foo.class
和 Bar.class
下面是加载 Bar 和 Foo 的类,并且想要动态调用 add
方法。
import java.io.File;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.net.URL;
import java.net.URLClassLoader;
public class Test {
public static void main(String... args) throws Throwable {
File classFile = new File("/usr/local");
ClassLoader classLoader = new URLClassLoader(new URL[]{classFile.toURI().toURL()});
Class fooClass = classLoader.loadClass("Foo");
MethodHandle mh = MethodHandles
.lookup()
.findVirtual(fooClass, "add", MethodType.methodType(int.class, int.class, int.class));
System.out.println((int)mh.invoke(2, 3));
}
}
下面是我得到的错误
Exception in thread "main" java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(Foo,int,int)int to (int,int)int
问题:
- 如何使用
MethodHandles
调用实现接口(interface)的类的方法? - 有没有办法避免
(int)mh.invoke(2, 3) 中的疯狂转换
?
最佳答案
您忘记再包含一个参数 - 一个实例,将在该实例上调用该方法:
Class<?> barClass = classLoader.loadClass("Bar");
Object barInstance = barClass.getConstructor().newInstance();
System.out.println(mh.invoke(barInstance, 2, 3));
此外,MethodHandle.invoke
的返回类型是 Object
,因此在这种情况下您无法避免强制转换。
关于java - 如何使用 MethodHandles 调用实现 Java 8 接口(interface)的类上的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53034978/