本文介绍了我可以从静态内部类访问外部类的字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有另一个静态内部类:

I have a class which has another static inner class:

class A {
    private List<String> list;

    public static class B {
        // I want to update list here without making list as static
        // I don't have an object for outer class
    }
}


推荐答案

正如您所看到的那样其他答案,你需要一个非静态内部类来做到这一点。

As you can see from other answers that you will need a non-static inner class to do that.

如果你真的不能使你的内部类非静态,那么你可以添加所需的getter和setter外部类中的方法,并通过从内部静态类内部创建外部类的实例来访问它们:

If you really cannot make your inner class non-static then you can add required getter and setter method in outer class and access them by creating an instance of outer class from inside inner static class:

public class A {
    private List<String> list = new ArrayList<String>();
    public List<String> getList() {
        return list;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public static class B {
        // i want to update list here without making list as static
        void updList() {
            A a = new A();
            a.setList(someOtherList);
            System.out.println(a.getList());
        }
    }
}

这篇关于我可以从静态内部类访问外部类的字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:32