不能访问封闭的类型实例。 [英] No enclosing instance of type is accessible.

查看:2530
本文介绍了不能访问封闭的类型实例。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整个代码是:

public class ThreadLocalTest {
    ThreadLocal<Integer> globalint = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return new Integer(0);
        }
    };


    public class MyThread implements Runnable{
        Integer myi;
        ThreadLocalTest mytest;

        public MyThread(Integer i, ThreadLocalTest test) {
            myi = i;
            mytest = test;
        }

        @Override
        public void run() {
            System.out.println("I am thread:" + myi);
            Integer myint = mytest.globalint.get();
            System.out.println(myint);
            mytest.globalint.set(myi);
        }
    }


    public static void main(String[] args){
        ThreadLocalTest test = new ThreadLocalTest();
        new Thread(new MyThread(new Integer(1), test)).start();
    }
}

为什么以下代码段为:

ThreadLocalTest test=new ThreadLocalTest();
    new Thread(new MyThread(new Integer(1),test)).start();

导致以下错误:


无法访问ThreadLocalTest类型的封闭实例。必须使用ThreadLocalTest类型的封闭实例限定
分配(egxnew A()
其中x是ThreadLocalTest的实例)。

No enclosing instance of type ThreadLocalTest is accessible. Must qualify the allocation with an enclosing instance of type ThreadLocalTest (e.g. x.new A() where x is an instance of ThreadLocalTest).






核心问题是:
i想要在静态方法中初始化内部类。
这里有两个解决方案:


The core problem is that: i want to initialize the inner class in the static methods. here are two solutions:


  1. 将内部类视为外部类

  1. make the inner class as outer class

使用外部引用,如:

new Thread( test.new MyRunnable(test))。start(); //使用测试对象创建新的

推荐答案

如果您将类 MyThread 更改为 static ,则可以消除此问题:

If you change class MyThread to be static, you eliminate the problem:

public static final class MyThread implements Runnable

由于你的 main()方法是静态的,如果不首先创建封闭类的实例,则不能依赖封闭类的非静态类型或字段。但更好的是,甚至不需要这样的访问,这是通过使有问题的类静态来实现的。

Since your main() method is static, you can't rely on non-static types or fields of the enclosing class without first creating an instance of the enclosing class. Better, though, is to not even need such access, which is accomplished by making the class in question static.

这篇关于不能访问封闭的类型实例。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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