2 Replies Latest reply on May 25, 2008 12:29 PM by ugn

    Altering Generics Information of Methods using Javassist

    simonringuette

      I have done numerous things using javassist but there is one thing I would really love to do and I have yet to find how so I'm hoping for some pointers. I would like to change methods return types from List to List. While I understand that this would not change the method bytecode (erasure technique), I'm doing that so that when using this code in a java 5 environment the programmer would be forced to use Lists of the given type.

      What i'm actually doing is from an XSD, i'm generating a model using JAXB 1. I'm then using javassist to instrument various behaviours into that JAXB model (like listeners, clone support and more) and generate a second "instrumented" model that i'm using for development.

      Any pointers on how to change the generic type of a return would be appreciated.

      Thanks

        • 1. Re: Altering Generics Information of Methods using Javassist
          simonringuette

          I have done further reading on how this is implemented by the compiler and finally found out the answer I was looking for.

          You can defenitely do that with javaassist. The key class is javassist.bytecode.SignatureAttribute.

          From a CtMethod, i've obtained the methodInfo I add a Signature attribute. You can do it with something like:

          CtMethod method = ....
          MethodInfo methodInfo = method.getMethodInfo();
          SignatureAttribute signatureAttribute = new SignatureAttribute(methodInfo.getConstPool(),
          "()Ljava/util/List<Ljava/lang/String;>;");
          methodInfo.addAttribute(signatureAttribute);


          If your more interesed in reading the signature with the generics inside, you can use the methodInfo.getAttribute(SignatureAttribute.tag).

          I hope this helped.


          • 2. Re: Altering Generics Information of Methods using Javassist
            ugn

            I'am interested in reading return and parameter types like Collection . With your suggestion it does not work for me. I just get somer annotations an thats it. If I work with mthod.getReturnType() i get Collection but not Collection. Does someone have an idea how to solve this problem?