I'm trying to make instances of anonymous classes using reflection. But ocassionally I've seen strange behaviour during instantination.
Please, look at these similar fragments of code
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();
}
}
This code works well, and the output expected
Instance initializing block
I'm final :)
Instance initializing block
I'm final :)
After this I've decided to change code in simple way (just added 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();
}
}
And here is output that I've got:
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)
As you may see - new instance hasn't been created.
Could anybody explain me, the reason of such changes?
Thanks
See Question&Answers more detail:os