9

I want to annotate a class dynamically to make it the more generic as possible:

public class Test<T> {

    @XmlAttribute(name = dynamicvalue)
    T[] data;

    public Test(String dynamicvalue) {
    }  
}

Is there any way to achieve something like this.

TA

2 Answers 2

4

No. Annotations are static class-level information and they can't be influenced by the values of instance fields (no, they can't influenced by the values of static fields either).

2

You can create new classes at runtime by loading in new bytecode, so in theory it should be possible (remember, the annotations are associated with the class, not the object). And you can use an API like Java Assist to help create them. There's an annotation package that you could look at.

It won't be easy.

3
  • 2
    If you go this route, note that you'll still have to create multiple classes with different annotations. This kind-of defeats the purpose of having a common class. Mar 26, 2010 at 11:58
  • I'm assuming that jlanza needs to do this to deal with some external API (maybe an XML serializer), otherwise you'd just use an instance variable.
    – Chad Okere
    Mar 27, 2010 at 13:18
  • The idea was to create a generic class for an item and then use the parent class annotation to be inherited, but changing automatically changing the name. The dynamic value depends on the class Template.
    – jlanza
    Mar 29, 2010 at 5:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.