我有一段Java 7的代码,其中我在使用MethodHandle。代码如下:
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
class HelloWorldApp {
public static void main(String[] args) {
MyMethodHandle obj = new MyMethodHandle();
obj.getToStringMH();
}
}
class MyMethodHandle {
public String getToStringMH() {
MethodHandle mh;
String s ;
MethodType mt = MethodType.methodType(String.class, char.class, char.class);
MethodHandles.Lookup lk = MethodHandles.lookup();
try {
mh = lk.findVirtual(String.class, "replace", mt);
} catch (NoSuchMethodException | IllegalAccessException mhx) {
throw (AssertionError)new AssertionError().initCause(mhx);
}
try {
s = (String) mh.invokeExact("daddy",'d','n');
}
catch(Exception e) {
throw (AssertionError)new AssertionError().initCause(e);
}
System.out.println(s);
return "works";
}
}
当我编译这个时:
javac HelloWorldApp.java
我收到了这样的错误消息:
我遇到了这个错误:
HelloWorldApp.java:23: error: unreported exception Throwable; must be caught or declared to be thrown
s = (String) mh.invokeExact("daddy",'d','n');
^
1 error
我哪里犯了错误?
(AssertionError)new AssertionError().initCause(mhx)
改写为new AssertionError(mhx)
。 - Peter Lawrey