thirdson / jsr-305

Automatically exported from code.google.com/p/jsr-305
0 stars 0 forks source link

Using generics may be a more natural way to specify the TypeQualifier #9

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
In the following example, the type checked can be obtained from the
generic. The generic helps ensure the type is consistent.

public static void main(String... args) {
    System.out.println("getTypeQualifier(MatchesPattern.Checker.class)= " +
getTypeQualifier(MatchesPattern.Checker.class));
}

public static Type getTypeQualifier(Class<? extends TypeQualifierValidator>
tqvClass) {
    for (Type type : tqvClass.getGenericInterfaces()) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            if (parameterizedType.getRawType() == TypeQualifierValidator.class)
                return parameterizedType.getActualTypeArguments()[1];
        }
    }
    throw new AssertionError();
}

public interface TypeQualifierValidator<A extends Annotation, T> {
    public
    @Nonnull
    When forConstantValue(@Nonnull A annotation, T value);
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface MatchesPattern {
    @RegEx
    String value();

    int flags() default 0;

    static class Checker implements TypeQualifierValidator<MatchesPattern,
String> {
        @Nonnull
        public When forConstantValue(MatchesPattern annotation, String value) {
            Pattern p = Pattern.compile(annotation.value(),
annotation.flags());
            if (p.matcher(value).matches())
                return When.ALWAYS;
            return When.NEVER;
        }

    }
}

Original issue reported on code.google.com by peter.la...@gmail.com on 27 Jan 2009 at 6:25