我的方法无法识别Java枚举类型 [英] Java Enum types not being recognized by my methods
问题描述
当前正在开发用于单人作业的代码气味检测器。我制作了一个抽象的CodeSmell类,其中有两个具体的子类-ClassLevelSmell和MethodLevelSmell。 CodeSmell类具有SmellType类型的受保护字段。构造函数示例如下:
Currently developing a code smell detector for a uni assignment. I have made an abstract CodeSmell class, with two concrete subclasses - ClassLevelSmell and MethodLevelSmell. The CodeSmell class has a protected field of type SmellType. A sample constructor is as follows:
public ClassLevelSmell(ClassDefinition classDef, SmellType type){
smellyClass = classDef;
this.smell = type;
}
SmellType是我定义的枚举,如下所示:
SmellType is an enum I defined, which looks like this:
public enum SmellType {
LONG_CLASS, LONG_METHOD, PRIMITIVE_OBSESSION, LONG_PARAM_LIST}
然后,我有了一个SmellDetector对象,其中有许多方法可以比较所分析的类和方法的统计信息(例如它们的行数,基本声明的数量等)并创建如果发现气味,则返回一个新的CodeSmell对象。因此,我的代码如下所示:
I then have a SmellDetector object, with numerous methods that compare the statistics of analyzed classes and methods (such as their number of lines, number of primitive declarations etc) and creates a new CodeSmell object if a smell is found. So my code for this looks like this:
private void detectLongClass(ClassDefinition classDef) {
if(classDef.getNumLines() > 250){
smells.add(new ClassLevelSmell(classDef, LONG_CLASS));
}
}
每个SmellDetector对象都有一个 smells ,CodeSmells的ArrayList。但是,当我尝试将SmellType LONG_CLASS传递到ClassLevelMethod的构造函数中时,我在日食中收到了编译器警告,告诉我 LONG_CLASS无法解析为变量。我在使用枚举类型时是否犯了一些错误?
Each SmellDetector object has a field smells, an ArrayList of CodeSmells. However, I'm getting a compiler warning in eclipse when I try to pass the SmellType LONG_CLASS into the constructor for the ClassLevelMethod, telling me "LONG_CLASS cannot be resolved to a variable". Am I making some mistake with the use of Enumerated types? What do?
推荐答案
要引用枚举值,您需要使用带类名的合格格式或使用静态导入。所以要么做到:
To reference enum values you either need to use the qualified form with the class name or use static imports. So either make it:
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枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!