我的方法无法识别Java Enum类型

时间:2011-04-20 13:37:07

标签: java enums

目前正在开发一种用于单一分配的代码气味检测器。我创建了一个抽象的CodeSmell类,它有两个具体的子类 - ClassLevelSmell和MethodLevelSmell。 CodeSmell类具有SmellType类型的受保护字段。示例构造函数如下:

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无法解析为变量”。我在使用枚举类型时犯了一些错误吗?怎么办?

2 个答案:

答案 0 :(得分:8)

要引用枚举值,您需要使用带有类名的限定表单或使用静态导入。所以要么做到:

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));

答案 1 :(得分:4)

试试这个:

smells.add(new ClassLevelSmell(classDef, SmellType.LONG_CLASS));