目前正在为大学作业开发代码气味检测器。我创建了一个抽象的 CodeSmell 类,它有两个具体的子类 - ClassLevelSmell 和 MethodLevelSmell。 CodeSmell 类有一个 SmellType 类型的 protected 字段。构造函数示例如下:
public ClassLevelSmell(ClassDefinition classDef, SmellType type){
smellyClass = classDef;
this.smell = type;
}
SmellType 是我定义的一个枚举,如下所示:
public enum SmellType {
LONG_CLASS, LONG_METHOD, PRIMITIVE_OBSESSION, LONG_PARAM_LIST}
然后,我有一个 SmellDetector 对象,其中包含许多方法,用于比较分析的类和方法的统计数据(例如它们的行数、原始声明的数量等),并在发现气味时创建一个新的 CodeSmell 对象。所以我的代码如下所示:
private void detectLongClass(ClassDefinition classDef) {
if(classDef.getNumLines() > 250){
smells.add(new ClassLevelSmell(classDef, LONG_CLASS));
}
}
每个 SmellDetector 对象都有一个字段 smells,即 CodeSmells 的 ArrayList。但是,当我尝试将 SmellType LONG_CLASS 传递到 ClassLevelMethod 的构造函数时,我在 Eclipse 中收到编译器警告,告诉我“LONG_CLASS 无法解析为变量”。我在使用枚举类型时犯了一些错误吗?做什么?
最佳答案
要引用枚举值,您需要使用带有类名的限定形式或使用静态导入。所以要么做到:
smells.add(new ClassLevelSmell(classDef, SmellType.LONG_CLASS));
或者这样做:
// at the top of your file:
import static packagename.SmellType.*;
smells.add(new ClassLevelSmell(classDef, LONG_CLASS));
关于我的方法无法识别 Java 枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5731214/