简体   繁体   English

可以在静态方法中实例化的匿名内部类是否可以访问包含类的实例成员?

[英]Can Anonymous inner class instantiated within a static method has access to instance members of containing class?

I want to understand better the visibility of instance fields of containing class to an Anonymous inner class (AIC) . 我想更好地理解包含类的实例字段对Anonymous内部类(AIC)的可见性。

There have been lots of talks that AIC has an implicit reference to the containing class' instance ( When exactly is it leak safe to use (anonymous) inner classes? ). 有很多关于AIC隐含引用包含类的实例的讨论( 当它确实是泄漏安全使用(匿名)内部类时? )。 With that logic, even when an AIC is instantiated within a static method, it should have access to the instance fields of the containing class. 使用该逻辑,即使在静态方法中实例化AIC,它也应该可以访问包含类的实例字段。 But I can't find a way to test this as the compiler gives errors. 但是由于编译器出错,我无法找到测试方法。

For eg, in the below code, I get: "Non-static field 's' can't be referred from a static context" by the compiler when I refer 's' within print() method of the AIC: 例如,在下面的代码中,我得到:当我在AIC的print()方法中引用's'时,编译器“无法从静态上下文中引用非静态字段'

public interface TestInterface {
    void print();
}


public class AICTest {
    public String s = "something";
    public static void main( String[] args ) {

        new TestInterface() {
            @Override
            public void print() {
                System.out.println( s ); **<-- compilation error**
            }
        }.print();

    }
}

Could you suggest if it's possible for the AIC instance to access 's' in the above example? 你能否建议AIC实例是否可以在上面的例子中访问's'?

Edit/Answer I want to clarify that I am aware that static methods have access to class members and instance methods have access to instance & class members. 编辑/回答我想澄清一点,我知道静态方法可以访问类成员,实例方法可以访问实例和类成员。 The confusion was more about the general statement that AIC always have an implicit reference to containing class' object. 混淆更多的是关于AIC总是隐含引用包含类'对象的一般声明。 This clearly is not the case for AIC initialised within a static method. 对于在静态方法中初始化的AIC,情况显然不是这样。 @shmosel shared a link which answers my question ( Is it possible to make anonymous inner classes in Java static? ): "So an anonymous class in a static context is roughly equivalent to a static nested class in that it does not keep a reference to the enclosing class, even though it's technically not a static class.". @shmosel共享一个回答我的问题的链接( 是否有可能在Java静态中创建匿名内部类? ): “因此静态上下文中的匿名类大致相当于静态嵌套类,因为它不保留对封闭的类,即使它在技术上不是静态类。“

You have to have an instance of AICTest to read 's' out of, since 's' is an instance variable. 你必须有一个AICTest实例才能读出's',因为's'是一个实例变量。 Here's an example that will work, representing your example modified to access an existing AICTest object that could potentially come from anywhere: 这是一个可行的示例,表示您的示例被修改为访问可能来自任何地方的现有AICTest对象:

class AICTest {
    public String s = "something";
    public static void main( String[] args ) {

        AICTest aic = new AICTest();

        new TestInterface() {
            @Override
            public void print() {
                System.out.println(aic.s);
            }
        }.print();

    }
}

To be clear, running 'main' does not create an instance of AICTest. 要清楚,运行'main'不会创建AICTest的实例。 You have to do a 'new' somewhere to create an instance of AICTest. 你必须在某个地方做一个'new'来创建一个AICTest实例。

Another option is to make 's' static. 另一种选择是让's'静止。 Then it isn't associated with any particular AICTest object, and so it exists even if you haven't instantiated an AICTest object: 然后它不与任何特定的AICTest对象相关联,因此即使您没有实例化AICTest对象它也存在:

class AICTest {
    public static String s = "something";
    public static void main( String[] args ) {

        new TestInterface() {
            @Override
            public void print() {
                System.out.println(s);
            }
        }.print();

    }
}

As you can see, I haven't added any visibility modifiers. 如您所见,我没有添加任何可见性修饰符。 So your idea about visibility was sound. 所以关于可见性的想法是合理的。 If it otherwise makes sense to access 's', the visibility is there in your code. 如果访问“s”是有意义的,那么代码中就会显示可见性。 The problem here has nothing to do with visibility. 这里的问题与可见性无关。

This may not be what you want, but you can: 这可能不是你想要的,但你可以:

interface TestInterface {
    void print();
}
class AICTest {
    public String s="something";
    public static void main(String[] args) {
        AICTest aicTest=new AICTest();
        new TestInterface() {
            @Override public void print() {
                System.out.println(aicTest.s);
            }
        }.print();
    }
}

The confusion was more about the general philosophy that AIC always have an implicit reference to containing class' object. 混淆更多的是一般的哲学,即AIC总是隐含地引用包含类的对象。 This clearly is not the case for AIC initialised within a static method. 对于在静态方法中初始化的AIC,情况显然不是这样。 @shmosel shared a link which answers my question (Is it possible to make anonymous inner classes in Java static?): "So an anonymous class in a static context is roughly equivalent to a static nested class in that it does not keep a reference to the enclosing class, even though it's technically not a static class.". @shmosel共享一个回答我的问题的链接(是否有可能在Java静态中创建匿名内部类?):“因此静态上下文中的匿名类大致相当于静态嵌套类,因为它不保留对封闭的类,即使它在技术上不是静态类。“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 静态方法无法访问类的实例成员 - Static method cannot access instance members of a class 访问匿名或本地内部类中的匿名或本地内部类 - Access an Anonymous or Local Inner Class Within an Anonymous or Local Inner Class Java:对外部类私有成员的匿名内部类实例初始化程序访问 - Java: Anonymous Inner Class Instance Initializer Access to Outer Class Private Members Java匿名内部类调用静态方法 - Java Anonymous Inner Class Calling Static Method 静态内部类如何访问外部类的所有静态数据成员和静态成员函数? - How does static inner class can access all the static data members and static member function of outer class? 在匿名类中使用最终字段,在方法内声明静态嵌套类,并在内部类内定义静态成员 - Using Final Fields in Anonymous Classes, Declaring Static Nested Class Inside a Method and Defining Static Members inside an Inner Class 外部类可以访问内部类的成员吗? - Can an outer class access the members of inner class? 访问内部匿名类成员 - Accessing inner anonymous class members 从内部匿名类访问外部匿名类的方法 - Access method of outer anonymous class from inner anonymous class 如何在main方法中访问匿名内部类? - How to access anonymous inner class in main method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM