Last active
January 6, 2016 11:52
-
-
Save psamsotha/a68b9dafb457b3168ed7 to your computer and use it in GitHub Desktop.
Stack Overflow http://stackoverflow.com/q/34560790/2587435
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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