简体   繁体   English

是否可以从Java中的外部对象访问隐藏字段?

[英]Is it possible to access hidden field from outside object in Java?

Consider a class, hiding member from superclass. 考虑一个对超类隐藏成员的类。 If implementing clone, then how to update both members correctly? 如果实现克隆,那么如何正确更新两个成员?

public class Wrapper implements Cloneable{
   protected Collection core;
   protected Wrapper(Collection core) {
      this.core = core;
   }
   public Wrapper clone() {
      try {
         Wrapper ans = (Wrapper) super.clone();
         ans.core = (Collection) core.getClass().newInstance();
         for(Object o : core) {
            ans.core.add( o.clone() );
         }
         return ans;
      }
      catch(CloneNotSupportedException e) {
         throw new AssertionError(e);
      }
   }
}

public class Child extend Wrapper {
   protected ArrayList core; // for simpler access
   public Child() {
      super(new ArrayList());
      this.core = (ArrayList) super.core;
   }
   public Child clone() {
      Child ans = (Child) super.clone();
      ans.core ... // how to update both core members?
      // ans.super.core ... ?
      // ans.this.core ... ?
   }
}

The standard way is to cast Child to Wrapper in order to access its hidden field. 标准方法是将Child WrapperWrapper以便访问其隐藏字段。

Simple example: 简单的例子:

public class Test {

public static class A {
    protected String field = "I'm class A";
}

public static class B extends A {
    protected String field = "I'm class B";
}

/**
 * @param args
 */
public static void main(String[] args) {
    B b = new B();
    System.out.println(b.field); // prints "I'm class B"
    System.out.println(((A) b).field); //prints "I'm class A"
}

}

But why do you hide the field? 但是,为什么要隐藏田野? This leads to programming errors and makes your code hard to read. 这会导致编程错误,并使您的代码难以阅读。 I would suggest accessing the field with getters and setters. 我建议使用getter和setter访问该领域。 In fact, i suggest declaring abstract getters and setters in Wrapper in order to force subclasses to provide a corresponding field. 实际上,我建议在Wrapper中声明抽象的getter和setter,以强制子类提供相应的字段。

Best regards, 最好的祝福,

sam SAM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM