zoukankan      html  css  js  c++  java
  • java中"no enclosing instance of type * is accessible"的解决方法

    这种情况一般发生在“在静态方法里面使用内部类”

    测试代码:

    public class Test {
    	public static void main(String[] args) {
    		A a = new A(1);
    	}
    	class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    	}
    }
    

      上面这份代码在main函数里面会发生编译错误,为了解决问题,让我们先看看编译器的提示:

    编译器告诉我们,没有可访问的Test类的实例,意味着下面将要使用实例,那个地方使用了呢?看后面的括号里面,"x.new A()",new A()实际上是x.new A(),其中x是Test的一个实例。所以我们可以先创建Test的一个实例,然后用这个实例的new方法new一个A()出来。

    于是可以改成下面的代码:

    public class Test {
    	public static void main(String[] args) {
    		Test test = new Test();
    		A a = test.new A(1);
    	}
    	class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    	}
    }
    

      明白了这一点就可以解释下面的代码了:

    public class Test {
    	public static void main(String[] args) {
    		Test test = new Test();
    		A a = test.new A(1);
    		
    		B b = new B(2);//这里的B不是一个内部类,所以不存在上述问题所以可以直接写new
    		
    		A.AA aa = a.new AA(3);
    	}
    	class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    		class AA {
    			int x;
    			AA() {}
    			AA(int x) {
    				this.x = x;
    			}
    		}
    	}
    }
    
    class B {
    	int x;
    	public B() {}
    	public B(int x) {
    		this.x = x;
    	}
    }
    

    或者用令外一种方法,将内部类改成静态的:

    public class Test {
    	public static void main(String[] args) {
    		A a = new A();
    	}
    	static class A {
    		int x;
    		public A() {}
    		public A(int x) {
    			this.x = x;
    		}
    	}
    }
    

      

  • 相关阅读:
    burpsuite 关于部分https抓包失败原因
    记一次对汉明科技无线运营系统审计的过程
    nmap script 总结
    python argparse总结
    unix 密码破解,zip破解总结
    python 反向shell后门
    结构体的不完整声明
    [转载][来自csdn]RTS和CTS是什么意思?
    博客开通成功
    system系统调用返回值判断命令是否执行成功
  • 原文地址:https://www.cnblogs.com/jklongint/p/4977230.html
Copyright © 2011-2022 走看看