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);
}
}
现在,它声明来自BayesianClassifier的非静态方法getVocabulary不能从静态上下文引用,我理解,但是该方法如何从调用的BayesianClassifier实例获取字段'词汇'的值这种方法?肯定必须可以不将整个词汇表作为参数传递,或者将类别BayesianClassifier的实例作为字段给出?
答案 0 :(得分:0)
您可以使用以下代码来使用它:
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);
}
}
答案 1 :(得分:0)
如评论中所述,可以使用Reflection完成。如果您无法将词汇作为参数传递,请在此处输入答案:Previous Answer to Same Question
如果您不想使用Reflection,您有两个选择:
选项1:
调用updateProbabilities
时只需传入Vocabulary对象。 Java是按值传递,但这并不意味着将复制和传递整个Vocabulary对象。这是here的解释。本质上,指向对象的指针的值将被传递,并且这样做只会占用一个&#34;指针&#34;的额外空间。
选项2:
创建Category
对象时,请将BayesianClassifier
添加为字段。