Search code examples
javaannotationscode-injectionjavassist

Javassist annotations MemberValue without Name


I've been adding annotations to a method using javassist. The only annotation that I couldn't add was:

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

because it doesn't allow me to add a member without a value, anny suggestions?

That's the way I've been adding annotations so far:

a = new Annotation("WebResult",  cpp);
a.addMemberValue("targetNamespace", new StringMemberValue("value", cpp));
attr.addAnnotation(a);

The problem is that a.addMemberValue("TransactionAttributeType.NOT_SUPPORTED"); does not compile because the syntax is not correct:

The method addMemberValue(Annotation.Pair) in the type Annotation is not applicable for the arguments (String)

I'm aware that there should be a value, but this annotation has no value.


Solution

  • I did not try this solution however looking on the internet the only thing that I found on this topic was a solution proposed into the JBoss dev forum that you can find here.

    According to this solution they found out by printing annotations from a regular class that "value" is the name to be used.

    So I suggest you to try this solution and then post here back in this answer if this worked for you.

    a = new Annotation("WebResult",  cpp);
    a.addMemberValue("value", new StringMemberValue("TransactionAttributeType.NOT_SUPPORTED", cpp));
    attr.addAnnotation(a);
    

    PS: I also suggest to specify the full name of the attribute, just to be sure that the runtime compiler get it right (e.g. com.my.package.TransactionAttributeType.NOT_SUPPORTED)

    EDIT

    As we noticed the solution proposed is adding the property to the annotation as a string new StringMemberValue("...")leading to this result:

    @TransactionAttribute("TransactionAttributeType.NOT_SUPPORTE‌​D")

    However this could be the wrong solution if your parameter should be something different then a string. That's why you should take a look here to the documentation of the MemberVale in Javassist where you can find all the subtypes that you can use.

    For example if your parameter is Java Class you should do something like that:

    a.addMemberValue("value", 
          new ClassMemberValue("com.package.classname", cpp));
    

    Or if your member is an enum you can add it to your annotation with something like this:

      EnumMemberValue emv = new EnumMemberValue(cpp);
      emv.setType("TransactionAttributeType");
      emv.setValue("NOT_SUPPORTED");
      a.addMemberValue("value", emv);