Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
GoogleCodeExporter opened this issue Apr 22, 2015 · 0 comments

Comments

@GoogleCodeExporter
Copy link

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 [email protected] on 27 Jan 2009 at 6:25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant