如果可以为应该抛出检查异常的方法编写字节码?
例如,除非方法声明它抛出检查的异常,否则以下 Java 类不会编译:
public class CheckedExceptionJava {
public Class<?> testChecked(String s) throws ClassNotFoundException {
return Class.forName(s);
}
}
虽然以下 Scala 等效项确实(因为 Scala 没有检查异常):
class CheckedException {
def testChecked( s : String ) = Class.forName( s )
}
即使生成的字节码几乎相同:
Compiled from "CheckedExceptionJava.java"
public class CheckedExceptionJava extends java.lang.Object{
public CheckedExceptionJava();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public java.lang.Class testChecked(java.lang.String) throws java.lang.ClassNotFoundException;
Code:
0: aload_1
1: invokestatic #2; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
4: areturn
}
Compiled from "CheckedException.scala"
public class CheckedException extends java.lang.Object implements scala.ScalaObject{
public CheckedException();
Code:
0: aload_0
1: invokespecial #24; //Method java/lang/Object."<init>":()V
4: return
public java.lang.Class testChecked(java.lang.String);
Code:
0: aload_1
1: invokestatic #11; //Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
4: areturn
}
问题:是否有可能(以及如何)生成不标记它的字节码,即使该方法中的代码没有处理它也会引发检查异常?