如何访问在匿名对象中声明的字段? [英] How to access fields declared inside anonymous object?

查看:97
本文介绍了如何访问在匿名对象中声明的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java允许您在匿名类中声明新字段,但是我不知道如何从外部访问它们,即使将它们设置为public也不允许我这样做.

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);
   }
}

我收到此编译器错误:

$ 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

为什么?

推荐答案

为什么?

这是因为Object是变量o的静态类型,并且Object没有属性x.出于完全相同的原因,以下代码无法编译:

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;
  }
}

希望您的Java直觉是正确的,并且您期望会失败.因此,只需将直觉移植到您的示例中即可.

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?

与在我的示例中访问x的方式相同:反射.

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.

这篇关于如何访问在匿名对象中声明的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆