我的方法被另一个 class 调用,如何从那个 class 获取变量而不将其作为参数传递?

How can my method, which is being called by another class, obtain a variable from that class without passing it as a parameter?

BayesianClassifier中的一个方法调用了下面的方法(Category的一个方法):

public void updateProbabilities(Map<String, int> woordfrequenties) {
    for (Map.Entry<String, int> woordfrequentie : woordfrequenties.entrySet()) {
        String woord = woordfrequentie.getKey();
        int frequentie = woordfrequentie.getValue();
        int index = BayesianClassifier.getVocabulary().indexOf(woord);
    }
}

现在,它声明不能从此处的静态上下文中引用来自 BayesianClassifier 的非静态方法 getVocabulary,我理解,但是该方法如何从实例中获取字段 'vocabulary' 的值调用此方法的 BayesianClassifier?如果不将整个词汇表作为参数传递,或者将 BayesianClassifier 的实例作为字段提供给 class 类别,这肯定是可能的?

您可以通过以下代码使用它:

public class Category {
private final BayesianClassifier bayesianClassifier;

public Category(BayesianClassifier bayesianClassifier) {
  this.bayesianClassifier = bayesianClassifier;
}

public void updateProbabilities(Map<String, int> woordfrequenties) {
    for (Map.Entry<String, int> woordfrequentie : woordfrequenties.entrySet()) {
        String woord = woordfrequentie.getKey();
        int frequentie = woordfrequentie.getValue();
        int index = bayesianClassifier.getVocabulary().indexOf(woord);
    }
} 

public class Category {
private BayesianClassifier bayesianClassifier;

public void setBayesianClassifier(BayesianClassifier bayesianClassifier) {
  this.bayesianClassifier = bayesianClassifier;
}

public void updateProbabilities(Map<String, int> woordfrequenties, BayesianClassifier bayesianClassifier) {
    for (Map.Entry<String, int> woordfrequentie : woordfrequenties.entrySet()) {
        String woord = woordfrequentie.getKey();
        int frequentie = woordfrequentie.getValue();
        int index = bayesianClassifier.getVocabulary().indexOf(woord);
    }
} 

public void updateProbabilities(Map<String, int> woordfrequenties, BayesianClassifier bayesianClassifier) {
        for (Map.Entry<String, int> woordfrequentie : woordfrequenties.entrySet()) {
            String woord = woordfrequentie.getKey();
            int frequentie = woordfrequentie.getValue();
            int index = bayesianClassifier.getVocabulary().indexOf(woord);
        }
    }

如评论中所述,可以通过反射来完成。如果您不能将词汇作为参数传递,那么请在此处找到答案:Previous Answer to Same Question

如果您不想使用反射,您有两个选择:

选项 1:

调用时传入Vocabulary对象即可updateProbabilities。 Java是按值传递,但这并不意味着整个Vocabulary对象将被复制和传递。这是解释here。本质上,将传递指向您的对象的指针的值,这样做只会占用一个 "pointer" 的额外 space。

选项 2:

创建 Category 对象时,将 BayesianClassifier 添加为字段。