异常: No enclosing instance of type xx is accessible. Must qualify (Java 内部类)

异常

前言. 开发时候遇到内部类的问题.

  • 异常
No enclosing instance of type SparkProgrammingGuide is accessible. Must qualify the allocation with an enclosing instance of type SparkProgrammingGuide (e.g. x.new A() where x is an instance of SparkProgrammingGuide).
  • 代码如下
	// 注意 
	static class GetLength implements Function<String, Integer> {
		public Integer call(String s) {
			return s.length();
		}
	}

	class Sum implements Function2<Integer, Integer, Integer> {
		public Integer call(Integer a, Integer b) {
			return a + b;
		}
	}

	// 继承方法的形式进行运行.
	// 特别注意 局部类 No enclosing instance of type XXX is accessible. Must qualify 异常.
	static int getTotalLengthByExtendsFunction(JavaSparkContext context) {

		int totalLength = 0;
		if (null != context) {

			JavaRDD<String> distFile = context.textFile("data/wordcount/spark-overview.txt");
			JavaRDD<Integer> linesRDD = distFile.map(new GetLength());
			totalLength = linesRDD.reduce(new Sum());
		}
		return totalLength;

	}

解决措施

  • 方法1
    将局部类设置为静态的. 类名前添加<static>关键字即可.
static class Sum implements Function2<Integer, Integer, Integer> {
		public Integer call(Integer a, Integer b) {
			return a + b;
		}
	}
  • 方法2
    通过类名.局部类名访问即可. 即如下的new ParentClassName().new GetLength().
JavaRDD<Integer> linesRDD = distFile.map(new ParentClassName().new GetLength());
  • 方法3
    不使用局部类即可. 作为非public类型类写在一个文件即可.

Reference

[1] JAVA在编写内部类时No enclosing instance of type XXX is accessible. Must qualify原因及解决.
[2] No enclosing instance of type 类名 is accessible. Must qualify the allocation with.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章