簡體   English   中英

是否可以從Java中的外部對象訪問隱藏字段?

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

考慮一個對超類隱藏成員的類。 如果實現克隆,那么如何正確更新兩個成員?

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 ... ?
   }
}

標准方法是將Child WrapperWrapper以便訪問其隱藏字段。

簡單的例子:

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

}

但是,為什么要隱藏田野? 這會導致編程錯誤,並使您的代碼難以閱讀。 我建議使用getter和setter訪問該領域。 實際上,我建議在Wrapper中聲明抽象的getter和setter,以強制子類提供相應的字段。

最好的祝福,

SAM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM