views:

63

answers:

2

Hi,

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  A: 

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).

Joachim Sauer
A: 

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.

Chad Okere
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.
Joachim Sauer
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
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