Skip to content

Instantly share code, notes, and snippets.

@psamsotha
Last active January 6, 2016 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psamsotha/a68b9dafb457b3168ed7 to your computer and use it in GitHub Desktop.
Save psamsotha/a68b9dafb457b3168ed7 to your computer and use it in GitHub Desktop.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.AnnotatedTypeVariable;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
public class AnnotationsTest {
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
public static @interface Bar {
int value() default 1;
}
public static class Foo<T> {
public void foo(Foo<@Bar T> t) {}
}
public static void main(String[] args) throws Exception {
Method method = Foo.class.getDeclaredMethod("foo", Foo.class);
Parameter[] ps = method.getParameters();
Executable executable = ps[0].getDeclaringExecutable();
AnnotatedParameterizedType type
= (AnnotatedParameterizedType)executable.getAnnotatedParameterTypes()[0];
print(type.getType(), "AnnotationsTest$Foo<T>");
AnnotatedTypeVariable typeVar
= (AnnotatedTypeVariable)type.getAnnotatedActualTypeArguments()[0];
print(typeVar.getType(), "T");
print(Arrays.toString(typeVar.getAnnotations()), "[@Bar (maybe.. maybe not)]");
print(Arrays.toString(typeVar.getDeclaredAnnotations()), "[@Bar (maybe.. maybe not)]");
AnnotatedType[] types = typeVar.getAnnotatedBounds();
print(Arrays.toString(types[0].getAnnotations()), "[@Bar (maybe.. maybe not)]");
print(Arrays.toString(types[0].getDeclaredAnnotations()), "[@Bar (maybe.. maybe not)]");
}
private static void print(Object actual, String expected) {
final String format = "actual: %s; expected: %s";
System.out.println(String.format(format, actual.toString(), expected));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment