将变量从静态内部 class 传递到顶部 class

passing variable from static inner class to top class

所以我想在我的静态嵌套 class 中设置我的顶级 classes 变量 foo 的值。我的最终目标是弄清楚如何将参数从 Map 方法传递到我正在编写的 MapReduce 程序中的 Reduce 方法。我将代码简化为只有必要的元素以提高可读性。

这是我的资料:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    static String top = "foo";

    public void setTop(String newValue) {
        this.top = newValue;
    }

    public static class InnerClass {
        String innerString = "bar";
        Ideone newOne = new Ideone();
        newOne.setTop(innerString ); //not legal

    }

    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Hello World " + top);
    }
}

在实际的 MapReduce 程序中,嵌套的 class 将是我的 Mapper,顶层 class 将是整个 MapReduce 程序的名称,我最终将其 Jar 和 运行 在我的 Hadoop 集群中。

问题不在于静态内部 class 而不是嵌套 class。它是 class 本身 - 这个可以工作:

public static class InnerClass {
    String innerString = "bar";
    Ideone newOne = new Ideone();
    {
       newOne.setTop(innerString ); //not legal
    }

}

或者在构造函数中调用 setTop。您在示例中选择的语法根本无效。

另一个提示: 不清楚为什么你有一个静态变量 top,它有一个非静态 setter,从另一个 [=21] 调用=] 通过构造一个虚拟对象,调用 setter。为什么不直接 Ideone.top = innerString;

将您的 InnerClass 定义替换为

public static class InnerClass {

    public void setOuterClassTop() {
        String innerString = "bar";
        Ideone newOne = new Ideone();
        newOne.setTop(innerString );
    }

}

它会通过调用 setOuterClassTop() 方法来工作。