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

前端 未结 2 1633
别那么骄傲
别那么骄傲 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 <K> void doSomething(K thing)
    

    You could use this code:

    SignatureWriter signature = new SignatureWriter();
    signature.visitFormalTypeParameter("K");
    
    // Ensure that <K> extends java.lang.Object
    {
        SignatureVisitor classBound = signature.visitClassBound();
        classBound.visitClassType(Type.getInternalName(Object.class));
        classBound.visitEnd();
    }
    
    // The parameter uses the <K> 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 = "<K:Ljava/lang/Object;>(TK;)V;"
    
    0 讨论(0)
  • 2021-02-13 14:07

    In my experience most on-the-fly bytecode generation libraries don't have good support for generic types; however erased classes work just fine (unless you want to introspect those classes later, of course).

    0 讨论(0)
提交回复
热议问题