As Marco stated, an anonymous class is the same as any other at the file and byte code level. It is just syntactic sugar at the language level, which makes it easy to write small classes.
In your example, x.getClass() not an abstract class. This is a subclass of AbstractClass , which by definition id() no longer abstract . This name probably has the name anon$1 .
Of course, if it were abstract, you could not create it. This is exactly what you are trying to do when assigning y . Your reflection is equivalent to y = anon.AbstractClass(); with overriding id() . Reflection is a run-time error, as this statement will be a compile-time error.
It is possible that (depending on the availability of other anonymous classes and their order) and will run without errors, but type "X":
Class<AbstractClass> abstractclass = (Class<AbstractClass>)Class.forName("anon$1"); // Note the different class name AbstractClass y = abstractclass.getConstructor().newInstance(); y.id(); // prints "X", not "Y"
In this moment...
main.y.id(); // should print "Y"
Nowhere in your code do you have a line that prints the character "Y", so there should be no reason to expect this.
source share