Export to GitHub

jsr-305 - issue #9

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


Posted on Jan 27, 2009 by Helpful Horse

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&lt;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; }

}

}

Status: New

Labels:
Type-Defect Priority-Medium