This is an interesting little thing I’ve encountered. I was messing around with anonymous types and I wrote something like:
public class Test {
public static void method(Object obj) {
System.out.println(obj.getClass().getName());
}
public static void main(String[] args) {
method(new Object() {
int n = 0;
});
}
}
Well, I was quite surprised when the result printed was in fact test.Test$1 which is the name of the class in which the anonymous object was defined (it’s still the same if you move the method that prints the type name to another class).
Can someone explain this behavior? Is this specified in the Java standard or is yet another “undefined behavior”?
If you look again, you’ll see that the class name printed out has a trailing
$1. Inner classes always get named by concatenating$and the inner class name to the containing class’ name. Anonymous classes simply get a number instead of a name. So effectively, the class name that’s getting printed out is saying “the first anonymous class contained in test.Test”.