This class does have a name. It's A$1
. However, you can't access this at compile time (the compiler creates A$1
for you). Thus, you can't access the field without reflection.
If you're in Eclipse, you can use Source menu (AltShiftS) → Convert Anonymous Class to Nested to convert it to a "real" class automatically.
Alternatively, you could have:
class A {
public static void main(String[] args) {
I o = new I() {
public int x = 0;
{
System.out.println("x: " + x++);
System.out.println("x: " + x++);
}
public int getX() { return x; }
};
System.out.println(o.getX());
}
interface I {
public int getX();
}
}
EDIT: Here's a really evil way to accomplish this that you should not do:
class A {
public static void main(String[] args) {
Object o = new Object() {
public int x = 0;
{
System.out.println("x: " + x++);
System.out.println("x: " + x++);
}
public Object clone() {
// BAD BAD BAD
return x;
}
};
try {
System.out.println(o.clone());
} catch (CloneNotSupportedException cnse) {
assert false;
}
}
}