Generating methods with generic types with Asm bytecode generator (ClassWriter)

前端 未结 2 1638
别那么骄傲
别那么骄傲 2021-02-13 13:34

Defining simple getters and setters is easy using Asm (and fortunately it is even explained in their FAQ). But one thing that is not mentioned, and for which I have been unable

2条回答
  •  余生分开走
    2021-02-13 14:01

    You can build the signature using ASM's SignatureWriter class.

    For example, suppose you wish to write the signature for this method:

    public  void doSomething(K thing)
    

    You could use this code:

    SignatureWriter signature = new SignatureWriter();
    signature.visitFormalTypeParameter("K");
    
    // Ensure that  extends java.lang.Object
    {
        SignatureVisitor classBound = signature.visitClassBound();
        classBound.visitClassType(Type.getInternalName(Object.class));
        classBound.visitEnd();
    }
    
    // The parameter uses the  type variable
    signature.visitParameterType().visitTypeVariable("K");
    
    // The return type uses the void primitive ('V')
    signature.visitReturnType().visitBaseType('V');
    
    signature.visitEnd();
    
    String signatureString = signature.toString();
    

    Which is equivalent to:

    String signatureString = "(TK;)V;"
    

提交回复
热议问题