Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access fields declared inside anonymous object?

Java lets you declare new fields inside anonymous classes, but I can't figure out how to access them from outside, even setting them to public doesn't let me.

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++);
           }
       };
       System.out.println(o.x);
   }
}

I get this compiler error:

$ javac A.java && java A
A.java:10: cannot find symbol
symbol  : variable x
location: class java.lang.Object
       System.out.println(o.x);
                           ^
1 error

Why?

like image 252
Dog Avatar asked Dec 11 '22 15:12

Dog


1 Answers

Why?

It's because Object is the static type of the variable o, and Object doesn't have the property x. The following fails to compile for the exact same reason:

public class X {
  public int x;

  public static void main(String[] args) {
    Object o = new X();
    o.x = 3;
  }
}

Hopefully, your Java intuition is right on this example and you expect this to fail. So just transplant that intuition to your example.

How to access fields declared inside anonymous object?

Same way as you'd access x in my example: reflection.

Object o = new X();
o.getClass().getField("x").setInt(o, 3);

Why does it let me make public fields if I can't use them?

If it didn't let you make public fields, even reflection wouldn't work for you, at least not as simply as above.

like image 91
Marko Topolnik Avatar answered Jan 17 '23 21:01

Marko Topolnik