匿名类混淆的动态构建
我正在尝试使用反射来制作匿名类的实例。但偶尔我在瞬时看到奇怪的行为。
请看这些类似的代码片段
public class HideAndSeek {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IllegalAccessException, InstantiationException{
final String finalString = "I'm final :)";
Object object2 = new Object(){
{
System.out.println("Instance initializing block");
System.out.println(finalString);
}
private void hiddenMethod() {
System.out.println("Use reflection to find me :)");
}
};
Object tmp = object2.getClass().newInstance();
}
}
此代码运行良好,并且预期输出
Instance initializing block
I'm final :)
Instance initializing block
I'm final :)
在此之后,我决定以简单的方式更改代码(刚刚添加了java.util.Calendar)
import java.util.Calendar;
public class HideAndSeek {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IllegalAccessException, InstantiationException{
final String finalString = "I'm final :)";
final Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime().toString()); //works well
Object object2 = new Object(){
{
System.out.println("Instance initializing block");
System.out.println(finalString);
//simply added this line
System.out.println(calendar.getTime().toString());
}
private void hiddenMethod() {
System.out.println("Use reflection to find me :)");
}
};
Object tmp = object2.getClass().newInstance();
}
}
这是我得到的输出:
Wed Aug 17 02:08:47 EEST 2011
Instance initializing block
I'm final :)
Wed Aug 17 02:08:47 EEST 2011
Exception in thread "main" java.lang.InstantiationException: HideAndSeek$1
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at HideAndSeek.main(HideAndSeek.java:29)
如您所见 - 尚未创建新实例。
谁能解释一下,这些变化的原因?
谢谢