Java: how to reference a non-static field of an outer class from a static nested class?

前提是你 提交于 2019-12-13 16:25:43

问题


Is there a way to refer to a non-static field of an outer class from a static nested class?

Please see my code below:

public class TestComponent {
    String value;

    public void initialize(String value) {
        this.value = value;
    }

    public static class TestLabel extends GenericForwardComposer {
        Label testLabel;
        @Override
        public void doAfterCompose(Component comp) throws Exception {
            super.doAfterCompose(comp);
            testLabel.setValue(value);
        }
    }
}

This code throws an error at testLabel.setValue(value) as I am trying to make a static reference to a non-static field. But, I need the value to be non-static and yet reference it in the static nested class's method. How do I do it?

You may notice how I instantiate TestComponent.java here: http://top.cs.vt.edu/~vsony7/patches/gfc.patch

The idea is to create two labels dynamically with two different values "Label 1" and "Label 2" and append them to two different Components i.e. vlayout1 and vlayout2. But, when I run this code, a label gets attached to each of the layouts but the value of both the labels is "Label 2". You can test this at:

The problem is that the two windows from testlabel.zul created by two calls to IncludeBuilder share the static class TestLabel. After the super.doAfterCompoe() the value of test label is set to "Label 2" in both the calls.

I am using Zk framework and ZK does not have an enclosing instance so the inner nested class TestLabel must be static.

Thanks, Sony


回答1:


Inner static classes cannot access member variables of the enclosing class without an object reference. Inner static classes act like top-level static classes, just packaged inside a class.

Nested classes tutorial.

Your best alternative may be to construct an instance passing the instance's value as a parameter, or call a method with it as a parameter.




回答2:


The inner class can't be static for this to work. It needs have access to the enclosing instance of TestComponent to reference value. Remove the static modifier.



来源:https://stackoverflow.com/questions/8281810/java-how-to-reference-a-non-static-field-of-an-outer-class-from-a-static-nested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!