I have a Java 7 code, where I’m playing with MethodHanlde. The code is :
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";
}
}
when I compile this :
javac HelloWorldApp.java
I get a error like this :
HelloWorldApp.java:23: error: unreported exception Throwable; must be caught or declared to be thrown
s = (String) mh.invokeExact("daddy",'d','n');
^
1 error
Where I’m making mistake?
As the Javadoc for MethodHandle.invokeExact states
This means you must catch
Throwableor declare your methodthrows Throwable.BTW As this throws a generic exception an alternative to
is to rethrow the Throwable with
While using Thread.stop(t) can be unpredictable if you stop another thread, it is predictable if you throw it for the current thread.
Note: You need to ensure your method "throws" the appropriate checked exception for the method you are calling as the compiler cannot ensure this is the case.