简体   繁体   中英

Declare Field as Parameterized List Using java assist

We can declare field like following code.

evalClass.addField(CtField.make("private java.util.List abc;", evalClass));

How can we declare field List<String> abc using java assist?

Done little bit research on CtField class. we can set through setGenericSignature.

        CtField f = new CtField(pool.get(List.class.getCanonicalName()), "abc", evalClass);
        f.setGenericSignature(getGenericSignature(relatedClass));
        evalClass.addField(f);

    private String getGenericSignature(Class relatedClass) throws BadBytecode {
        String fieldSignature = "L" + List.class.getCanonicalName().replace(".", "/") + "<L" + String.class.getCanonicalName().replace(".", "/") + ";>;";
        return  SignatureAttribute.toClassSignature(fieldSignature).encode();
    }

First, generics are not supported by Javassist. From the Javassist documentation :

Generics

The lower-level API of Javassist fully supports generics introduced by Java 5. On the other hand, the higher-level API such as CtClass does not directly support generics. However, this is not a serious problem for bytecode transformation.

The generics of Java is implemented by the erasure technique. After compilation, all type parameters are dropped off. For example, suppose that your source code declares a parameterized type Vector:

 Vector<String> v = new Vector<String>(); String s = v.get(0); 

The compiled bytecode is equivalent to the following code:

 Vector v = new Vector(); String s = (String)v.get(0); 

So when you write a bytecode transformer, you can just drop off all type parameters. Because the compiler embedded in Javassist does not support generics , you must insert an explicit type cast at the caller site if the source code is compiled by Javassist, for example, through CtMethod.make(). No type cast is necessary if the source code is compiled by a normal Java compiler such as javac.

So you can basically use the method you wrot in your question in order to add a List without generic specification and that's gonna do the work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM