Java:如何从静态嵌套类中引用外部类的非静态字段? [英] Java: how to reference a non-static field of an outer class from a static nested class?

查看:151
本文介绍了Java:如何从静态嵌套类中引用外部类的非静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从静态嵌套类中引用外部类的非静态字段?

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);
        }
    }
}

当我尝试对非静态字段进行静态引用时,此代码在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?

您可能会注意到我如何在此处实例化TestComponent.java: http://top.cs.vt.edu/~vsony7/patches/gfc.patch

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

这个想法是用两个不同的值"Label 1"和"Label 2"动态创建两个标签,并将它们附加到两个不同的组件,即vlayout1和vlayout2.但是,当我运行此代码时,标签会附加到每个布局上,但是两个标签的值均为标签2".您可以在以下位置进行测试:

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:

问题在于,两次调用IncludeBuilder创建的来自testlabel.zul的两个窗口共享静态类TestLabel.在super.doAfterCompoe()之后,两个调用中的test label的值均设置为"Label 2".

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.

我正在使用Zk框架,并且ZK没有封闭实例,因此内部嵌套类TestLabel必须是静态的.

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

谢谢, 索尼

推荐答案

内部类不能静态运行.它需要访问TestComponent的封闭实例以引用value.删除静态修饰符.

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.

这篇关于Java:如何从静态嵌套类中引用外部类的非静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆