[英]How to use MethodHandles to call a method on the class that implements an interface in Java 8?
public interface Foo {
int add(int x, int y);
}
public class Bar implements Foo {
int add(int x, int y) {
return x+y;
}
}
Now Imagine I have Foo.class
and Bar.class
in /usr/local
现在想象一下我在
/usr/local
有Foo.class
和Bar.class
Below is the class that loads both Bar and Foo and want want to call the add
method dynamically. 下面是同时加载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));
}
}
Below is the error I get 以下是我得到的错误
Exception in thread "main" java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(Foo,int,int)int to (int,int)int
Questions: 问题:
MethodHandles
to invoke a method of a class that implements an interface? MethodHandles
调用实现接口的类的方法? (int)mh.invoke(2, 3)
? (int)mh.invoke(2, 3)
疯狂转换? You forgot to include one more argument - an instance, on which the method will be invoked: 您忘记了再添加一个参数-一个实例,在该实例上将调用该方法:
Class<?> barClass = classLoader.loadClass("Bar");
Object barInstance = barClass.getConstructor().newInstance();
System.out.println(mh.invoke(barInstance, 2, 3));
Also, the return type of the MethodHandle.invoke
is Object
, thus you can't avoid cast in this case. 另外,
MethodHandle.invoke
的返回类型为Object
,因此在这种情况下您无法避免MethodHandle.invoke
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.