Java – method for generating generic types using ASM bytecode generator (classwriter)

Defining simple getters and setters is easy to use ASM (fortunately, even in their FAQs) But there's one thing I didn't mention, so I can't find the document. How to use generic type information to implement it

I can actually easily determine the generic type information itself (because the code will take existing fields and / or methods, and there is a complete generic type processing and solution) I only need to generate generic versions for types that contain generic types

I hope this can be as simple as modifying the signature ASM classwriter / methodvisitor call, but some comments in the document indicate that it may not be so easy (because generic information is stored in a different location from general information)

Edit: it looks like the entry point is "classwriter. Visitfield / method (...., string signature) – note that it is a" description "containing normal non generic class information, but the term" signature "(in JLS) specifically refers to generic - including type information

Solution

You can use ASM's signaturewriter class to build signatures

For example, suppose you want to write a signature for this method:

public <K> void doSomething(K thing)

You can 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();

This is equivalent to:

String signatureString = "<K:Ljava/lang/Object;>(TK;)V;"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>