why is this code not compiling with javac but has

2019-04-07 14:00发布

问题:

the following code:

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Constraint(validatedBy = {
        MinTimeIntCoConstraintValidator.class, 
        MinTimeIntCoListConstraintValidator.class,
        MinTimeDoubleCoConstraintValidator.class, 
        MinTimeDoubleCoListConstraintValidator.class,
        })
@Documented
public @interface MinTimeValueCo
{
    int value();
    String message() default "value does not match minimum requirements";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default {};
}

compiled in eclipse but fails to compile in sun/oracle compiler:

> MinTimeValueCo.java:19: illegal start of expression
>     [javac]       })
>     [javac]       ^
>     [javac] 1 error

This happened because of the comma after MinTimeDoubleCoListConstraintValidator.class,.

when I removed the comma it works fine:

@Constraint(validatedBy = {
        MinTimeIntCoConstraintValidator.class, 
        MinTimeIntCoListConstraintValidator.class,
        MinTimeDoubleCoConstraintValidator.class, 
        MinTimeDoubleCoListConstraintValidator.class
        })

I am using jdk 1.6.0.10.
Do you know why this is illegal and compiling in eclipse?

回答1:

This is a bug in Java 6's javac. The JLS allows trailing commas in some places and the Eclipse compiler follows the standard here while Java 6 never allows trailing commas anywhere.

You can try to compile your code with javac from Java 7 with the options -source 6 -target 6 (to get Java 6 compatible byte code). If the bug is still there, file it. It might get fixed.



回答2:

You have a , at the end of MinTimeDoubleCoListConstraintValidator.class, it is looking for another expression in the list.



回答3:

It looks like you are declaring some sort of array of constraints. You are placing an extra comma (,) after your last constraint, thus making the compiler expect some other value together with the ones you already have. Try doing this:

@Constraint(validatedBy = {
        MinTimeIntCoConstraintValidator.class, 
        MinTimeIntCoListConstraintValidator.class,
        MinTimeDoubleCoConstraintValidator.class, 
        MinTimeDoubleCoListConstraintValidator.class
        })


回答4:

By having a comma after MinTimeDoubleCoListConstraintValidator.class, the java compiler thinks there should be another value. Eclipse accepts the trailing comma, but javac does not.