
在Java中,当需要在另一个包中的类的方法中创建受保护嵌套类型的列表时,直接引用受保护的嵌套类可能会遇到访问限制。一种有效的解决方案是创建一个公共接口,并让嵌套类实现该接口。这样,就可以通过引用该公共接口来创建列表,从而绕过访问限制。
问题背景
假设我们有一个类SomeClass,其中包含一个受保护的嵌套类Nested。现在,我们想在另一个包中的类MyClass的方法中创建一个Nested类型的列表。由于Nested是受保护的,直接引用它可能会导致编译错误。
解决方案:使用公共接口
立即学习“Java免费学习笔记(深入)”;
// SomeClass.java
package stuff;
public class SomeClass {
  public interface NestedInterface {
    int getX();
  }
  protected class Nested implements NestedInterface {
    int x;
    public Nested setX(int arg) {
      x = arg;
      return this;
    }
    public int getX() {
      return x;
    }
  }
  public Nested make(int x) {
    return new Nested().setX(x);
  }
}// SomeClass.java
package stuff;
public class SomeClass {
  public interface NestedInterface {
    int getX();
  }
  protected class Nested implements NestedInterface {
    int x;
    public Nested setX(int arg) {
      x = arg;
      return this;
    }
    public int getX() {
      return x;
    }
  }
  public Nested make(int x) {
    return new Nested().setX(x);
  }
}// SomeClass.java
package stuff;
public class SomeClass {
  public interface NestedInterface {
    int getX();
  }
  protected class Nested implements NestedInterface {
    int x;
    public Nested setX(int arg) {
      x = arg;
      return this;
    }
    public int getX() {
      return x;
    }
  }
  public NestedInterface make(int x) {
    return new Nested().setX(x);
  }
}// MyClass.java
package project;
import java.util.List;
import java.util.ArrayList;
import stuff.SomeClass;
import stuff.SomeClass.NestedInterface;
public class MyClass {
  public SomeClass instance;
  public List<NestedInterface> method() {
    List<NestedInterface> list = new ArrayList<>();
    list.add(instance.make(1));
    list.add(instance.make(2));
    return list;
  }
}完整代码示例
// SomeClass.java
package stuff;
public class SomeClass {
  public interface NestedInterface {
    int getX();
  }
  protected class Nested implements NestedInterface {
    int x;
    public Nested setX(int arg) {
      x = arg;
      return this;
    }
    public int getX() {
      return x;
    }
  }
  public NestedInterface make(int x) {
    return new Nested().setX(x);
  }
}// MyClass.java
package project;
import java.util.List;
import java.util.ArrayList;
import stuff.SomeClass;
import stuff.SomeClass.NestedInterface;
public class MyClass {
  public SomeClass instance;
  public List<NestedInterface> method() {
    List<NestedInterface> list = new ArrayList<>();
    list.add(instance.make(1));
    list.add(instance.make(2));
    return list;
  }
}注意事项
总结
通过创建一个公共接口,并让受保护的嵌套类实现该接口,我们可以有效地解决在另一个包中创建受保护嵌套类列表的问题。这种方法不仅可以绕过访问限制,还可以提高代码的灵活性和可维护性。
以上就是使用公共接口解决Java中受保护嵌套类的列表问题的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号