通过引用 Class 避免访问静态字段?

Accessing static field avoided by referencing Class?

我不明白为什么这行得通,请帮助教育我。

Config CFIG = new Config();
Tile selectedTile = CFIG.tileGallery.get(1);
System.out.println("This is the name:" + selectedTile.getName());
Feature selectedFeature = CFIG.featureGallery.get(3);
System.out.println("This is the name:" + selectedFeature.getName()+ 
    " " + selectedFeature.getEffect(0));

我初始化了对象CFIG,它同时设置了ClassConfigtileGalleryA​​rrayList和featureGalleryArrayList的成员变量。当我 运行 代码时,它会工作,输出选定的测试值。但是,对于这两个声明性语句,Netbeans 都会发出 "Accessing static field "

的警告

使用 "Replace with class reference" 的提示,将语句更改为:

Tile selectedTile = Config.tileGallery.get(1);
Feature selectedFeature = Config.featureGallery.get(3);

当我运行它时,它仍然有效!

问题,配置。不识别从哪个 Config 对象调用数据。现在我只有一个 Config 对象存在,但即使我初始化第二个 Config 对象,它仍然不会显得混乱。

这是怎么回事?

编辑:andih 想知道 Config Class 的代码是什么。我没有添加它,因为它不多,而且你可以很容易地假设它做了什么,因为它与这个问题有关。但是,以防万一。

public class Config {
    public static ArrayList<Tile> tileGallery;
    public static ArrayList<Feature> featureGallery;

    public Config (){
        this.tileGallery = Tile.ReadTileXML();
        this.featureGallery = Feature.ReadFeatureXML();
    }
}

static关键字表示该字段属于class比class的实例。即使你创建了一百个对象,这个字段也会在它们之间共享。 来自每个实例的这些静态字段 "tileGallery" 和 "featureGallery" 将指向内存中的同一个对象。

静态变量在class加载时只在class区域获取一次内存。

没有你的 Config class 的确切代码,这很难说,但看起来你的 Config class 使用静态字段,如

   public class Config {
      public Config() { 
         titleGallery = new ArrayList();
         titleTallery.add(new Title());
      }

      public static List<Title> titleGalery;
    }

提示就是这么说的。

在这种情况下,您的所有 Config 个实例共享相同的 titleGalery,您可以通过 Config.titleGalery.

访问它们

如果您想要不同的 Config 具有不同值的实例,您必须删除 static 关键字以获得独立的实例字段。

public class Config {
      public Config() { 
         titleGallery = new ArrayList();
         titleGallery.add(new Title());
      }

      // old: public static List<Title> titleGalery;
      public List<Title> titleGalery;
    }