这个问题在这里已经有了答案:
Java - No enclosing instance of type Foo is accessible
(7 个回答)
7年前关闭。
整个代码是:
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();
导致以下错误:
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).
核心问题在于:
我想在静态方法中初始化内部类。
这里有两个解决方案:
new Thread(test.new MyRunnable(test)).start();//Use test object to create new
最佳答案
如果换类 MyThread
是静态的,你消除了问题:
public static final class MyThread implements Runnable
由于您的
main()
方法是静态的,如果不首先创建封闭类的实例,就不能依赖封闭类的非静态类型或字段。不过,更好的是甚至不需要这样的访问,这是通过使有问题的类成为静态来实现的。
关于java - 没有封闭的类型实例是可访问的。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471664/