異常: 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.

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