5
如果可以爲應該拋出檢查異常的方法編寫字節碼?scala生成的字節碼如何丟棄檢查的異常?
例如下面的Java類不能編譯,除非方法聲明它拋出檢查異常:
public class CheckedExceptionJava {
public Class<?> testChecked(String s) throws ClassNotFoundException {
return Class.forName(s);
}
}
雖然下面的斯卡拉相當於做(因爲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
}
問題:是否有可能(以及如何)生成的字節碼不標記它會拋出一個檢查的異常,即使該方法內的代碼不處理它?
哦,我明白了。可能用像javassist這樣的工具? :) http://bit.ly/gNzXfA – OscarRyz 2010-12-02 16:45:02