使用Java 8是否可以验证/断言常量是编译时常量?

时间:2019-05-09 17:08:18

标签: java java-8

我想进行一个JUnit测试,以验证特定常量是否为编译时常量。 我将如何去做?

我找到了Scala的解决方案,但我希望使用纯Java。
Is there a way to test at compile-time that a constant is a compile-time constant?

根本原因:

The value for annotation attribute ApiModelProperty.allowableValues must be a constant expression

我在单元测试中想要的是:
    validateCompileTimeConstant(SomeClass.CONSTANT_VALUE, "Message Here!!");
用法
    @ApiModelProperty(name = "name", required = true, value = "Name", allowableValues=SomeClass.API_ALLOWABLE_VALUES, notes=SomeClass.API_NOTES)
    private String name;
某类
public enum SomeClass {
    BOB(4,  "Bob"),//
    TED(9,  "Ted"),//
    NED(13, "Ned");

    public static final String API_ALLOWABLE_VALUES = "4,9,13,16,21,26,27,170";
    public static final String API_NOTES = "4 - Bob\n" +
                                           "9 - Ted\n" +
                                           "13 - Ned";

    public int code;
    public String desc;

    private ContentCategoryCode(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public static final String apiAllowableValues() {
        StringBuilder b = new StringBuilder();
        for (ContentCategoryCode catCode : values()) {
            b.append(catCode.code);
            b.append(',');
        }
        b.setLength(b.length()-1);
        return b.toString();
    }

    public static final String apiNotes() {
        StringBuilder b = new StringBuilder();
        for (ContentCategoryCode catCode : values()) {
            b.append(catCode.code).append(" - ").append(catCode.desc);
            b.append('\n');
        }
        b.setLength(b.length()-1);
        return b.toString();
    }
}

2 个答案:

答案 0 :(得分:3)

Error Prone项目有一个@CompileTimeConstant批注,可用于强制执行此操作。

这不是与JUnit一起运行的测试,而是在编译时强制执行此(和其他错误模式)的编译器插件。

以下是文档:https://errorprone.info/bugpattern/CompileTimeConstant

答案 1 :(得分:1)

我最终创建了自己的注释,因为与使用“容易出错”相比,它所需的设置更少。

注释类:

@Target(ElementType.METHOD)
public @interface TestCompileTimeConstant {
    public String key() default "";
}

JUnit测试:

public class SomeClassTest {

    @Test
    public void test() {
        assertEquals(SomeClass.API_ALLOWABLE_VALUES, SomeClass.apiAllowableValues());
        assertEquals(SomeClass.API_NOTES, SomeClass.apiNotes());
    }

    @Test
    @TestCompileTimeConstant(key=SomeClass.API_ALLOWABLE_VALUES)
    public void testIsCompileTimeConstant1() {
        //Pass - If this doesn't compile, you need to make sure API_ALLOWABLE_VALUES doesn't call any methods.
    }

    @Test
    @TestCompileTimeConstant(key=SomeClass.API_NOTES)
    public void testIsCompileTimeConstant2() {
        //Pass - If this doesn't compile, you need to make sure API_NOTES doesn't call any methods. 
    }
}