Intelligent annotation

I created a lot of annotations in my life and now come to the strange case that I need this annotation, and I don’t think that it is supported by Java at all. Please tell me that I am right or wrong.

Here is my annotation:

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface DetailsField { public String name(); } 

And now the question! I would like the default value of the name () function to be the name of the field in which I posted the annotation.

I don’t know exactly how the class handler handles annotations, I’m sure that this is not implemented in the standard class loader, but can it possibly be achieved using the bytecode toolkit during class loading by the user class loader? (I'm sure if this is the only solution, I would find a way, just curious)

Any ideas? Or do I really want?

+4
source share
1 answer

I think you can use bytecode (when loading the class) to get this working, but it seems like a very complex and possibly not portable solution.

The best solution to your problem is to create a class that decorates (a-la Decorator design template) an instance of your annotation with name calculation logic.

[Edit: added definition of name () in interface]

 package p1; import java.lang.annotation.*; import java.lang.reflect.*; public class A { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface DetailsField { public int n1(); public String name() default ""; } public static class Nameable implements DetailsField { private final DetailsField df; private final Field f; public Nameable(Field f) { this.f = f; this.df = f.getAnnotation(DetailsField.class); } @Override public Class<? extends Annotation> annotationType() { return df.annotationType(); } @Override public String toString() { return df.toString(); } @Override public int n1() { return df.n1(); } public String name() { return f.getName(); } } public class B { @DetailsField(n1=3) public int someField; } public static void main(String[] args) throws Exception { Field f = B.class.getField("someField"); Nameable n = new Nameable(f); System.out.println(n.name()); // output: "someField" System.out.println(n.n1()); // output: "3" } } 
+4
source

All Articles