No enclosing instance of type is accessible. [duplicate]

こ雲淡風輕ζ 提交于 2019-12-20 14:14:29

问题


The whole code is:

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

why the following snippet:

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

cause the following error:

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).


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

  1. make the inner class as outer class

  2. use outer reference like :

new Thread(test.new MyRunnable(test)).start();//Use test object to create new


回答1:


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

public static final class MyThread implements Runnable

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.




回答2:


Since MyThread is an inner class you have to access it using an instance of MyThreadTest:

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


来源:https://stackoverflow.com/questions/12471664/no-enclosing-instance-of-type-is-accessible

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