我刚刚开始使用 Java,但在使用以下代码时遇到了问题。我正在使用类似的方法从静态方法调用非静态 apply 方法,但我认为它不是很有效。我设置了需要应用的规则的数组列表,但我无法让它工作。
ClassificationRule rules = new RuleFirstOccrnc();
ClassificationRule rules1 = new RuleOccrncCount();
rules.apply(aUserInput);
rules1.apply(aUserInput);
尝试从 ClassificationRule 调用 apply() 方法时收到此错误“对于 ArrayList 类型,未定义方法 apply(String)”。任何帮助将不胜感激!
package tweetClassification;
import java.util.ArrayList;
public class PrioritRuls {
//Set of rules to be applied
final static ArrayList<ClassificationRule> rulesA
= new ArrayList<ClassificationRule>();
static{
rulesA.add( new RuleFirstOccrnc() );
rulesA.add( new RuleOccrncCount() );
}
// *******************************************
public static void prioritize( final String aUserInput ){
rulesA.apply(aUserInput); //ERROR
// The method apply(String) is undefined
// for the type ArrayList<ClassificationRule>
}
}
package tweetClassification;
public class ClassificationRule {
// *******************************************
public void apply (final String aUserInput) {
apply( aUserInput );
}
}
最佳答案
正确,因为您正在调用数组列表对象的 apply
方法,而不是数组列表的内容。
将其更改为类似的内容
rulesA.get(0).apply()
或者,如果您想在每个元素上调用它,则需要遍历列表。
for (ClassificationRule rule:rulesA){
rule.apply(aUserInput);
}
关于java - 从对象数组列表中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10067349/