问题
I am trying to do some Java annotation magic. I must say I am still catching up on annotation tricks and that certain things are still not quite clear to me.
So... I have some annotated classes, methods and fields. I have a method, which uses reflection to run some checks on the classes and inject some values into a class. This all works fine.
However, I am now facing a case where I need an instance (so to say) of an annotation. So... annotations aren't like regular interfaces and you can't do an anonymous implementation of a class. I get it. I have looked around some posts here regarding similar problems, but I can't seem to be able to find the answer to what I am looking for.
I would basically like to get and instance of an annotation and be able to set some of it's fields using reflection (I suppose). Is there at all a way to do this?
回答1:
Well, it's apparently nothing all that complicated. Really!
As pointed out by a colleague, you can simply create an anonymous instance of the annotation (like any interface) like this:
MyAnnotation:
public @interface MyAnnotation
{
String foo();
}
Invoking code:
class MyApp
{
MyAnnotation getInstanceOfAnnotation(final String foo)
{
MyAnnotation annotation = new MyAnnotation()
{
@Override
public String foo()
{
return foo;
}
@Override
public Class<? extends Annotation> annotationType()
{
return MyAnnotation.class;
}
};
return annotation;
}
}
Credits to Martin Grigorov.
回答2:
The proxy approach, as suggested in Gunnar's answer is already implemented in GeAnTyRef:
Map<String, Object> annotationParameters = new HashMap<>();
annotationParameters.put("name", "someName");
MyAnnotation myAnnotation = TypeFactory.annotation(MyAnnotation.class, annotationParameters);
This will produce an annotation equivalent to what you'd get from:
@MyAnnotation(name = "someName")
Annotation instances produced this way will act identical to the ones produced by Java normally, and their hashCode
and equals
have been implemented properly for compatibility, so no bizarre caveats like with directly instantiating the annotation as in the accepted answer. In fact, JDK internally uses this same approach: sun.reflect.annotation.AnnotationParser#annotationForMap.
The library itself is tiny and has no dependencies.
Disclosure: I'm the developer behind GeAnTyRef.
回答3:
You can use sun.reflect.annotation.AnnotationParser.annotationForMap(Class, Map)
:
public @interface MyAnnotation {
String foo();
}
public class MyApp {
public MyAnnotation getInstanceOfAnnotation(final String foo) {
MyAnnotation annotation = AnnotationParser.annotationForMap(
MyAnnotation.class, Collections.singletonMap("foo", "myFooResult"));
}
}
Downside: Classes from sun.*
are subject to change in later versions (allthough this method exists since Java 5 with the same signature) and are not available for all Java implementations, see this discussion.
If that is a problem: you could create a generic proxy with your own InvocationHandler
- this is exactly what AnnotationParser
is doing for you internally. Or you use your own implementation of MyAnnotation
as defined here. In both cases you should remember to implement annotationType()
, equals()
and hashCode()
as the result is documented specifically for java.lang.Annotation
.
回答4:
You could use an annotation proxy such as this one from the Hibernate Validator project (disclaimer: I'm a committer of this project).
回答5:
I did this for adding annotation reference on my weld unit test:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser {
String value() default "foo";
@SuppressWarnings("all")
static class Literal extends AnnotationLiteral<AuthenticatedUser> implements AuthenticatedUser {
private static final long serialVersionUID = 1L;
public static final AuthenticatedUser INSTANCE = new Literal();
private Literal() {
}
@Override
public String value() {
return "foo";
}
}
}
usage:
Bean<?> createUserInfo() {
return MockBean.builder()
.types(UserInfo.class)
.qualifiers(AuthenticatedUser.Literal.INSTANCE)
.create((o) -> new UserInfo())
.build();
}
回答6:
Rather crude way using the proxy approach with the help of Apache Commons AnnotationUtils
public static <A extends Annotation> A mockAnnotation(Class<A> annotationClass, Map<String, Object> properties) {
return (A) Proxy.newProxyInstance(annotationClass.getClassLoader(), new Class<?>[] { annotationClass }, (proxy, method, args) -> {
Annotation annotation = (Annotation) proxy;
String methodName = method.getName();
switch (methodName) {
case "toString":
return AnnotationUtils.toString(annotation);
case "hashCode":
return AnnotationUtils.hashCode(annotation);
case "equals":
return AnnotationUtils.equals(annotation, (Annotation) args[0]);
case "annotationType":
return annotationClass;
default:
if (!properties.containsKey(methodName)) {
throw new NoSuchMethodException(String.format("Missing value for mocked annotation property '%s'. Pass the correct value in the 'properties' parameter", methodName));
}
return properties.get(methodName);
}
});
}
The types of passed properties are not checked with the actual type declared on the annotation interface and any missing values are discovered only during runtime.
Pretty similar in function to the code mentioned in kaqqao's answer (and probably Gunnar's Answer as well), without the downsides of using internal Java API as in Tobias Liefke's answer.
回答7:
You can also absolutely stupidly (but simply) create a dummy annotation target and get it from there
@MyAnnotation(foo="bar", baz=Blah.class)
private static class Dummy {}
And
final MyAnnotation annotation = Dummy.class.getAnnotation(MyAnnotation.class)
Creating method/parameter targeted annotation instances may be a little more elaborate, but this approach has the benefit of getting the annotation instance as the JVM would normally do. Needless to say it is as simple as it can get.
来源:https://stackoverflow.com/questions/16299717/how-to-create-an-instance-of-an-annotation