使用Asm字节码生成器(ClassWriter)生成具有泛型类型的方法 [英] Generating methods with generic types with Asm bytecode generator (ClassWriter)
问题描述
我实际上可以确定泛型类型信息本身很容易(因为代码将采用现有的字段和/或方法,并且存在完整的泛型类型处理和分辨率)。我只需要为包含泛型类型的类型生成泛型版本。
我希望这与修改Asm ClassWriter / MethodVisitor调用的签名一样简单,但一些注释在文档中指出它可能并不那么容易(因为泛型信息与常规信息存储在不同的位置)。
编辑:看起来像入口点是ClassWriter.visitField / Method(....,String signature) - 注意它是包含正常非泛型类信息的描述,但术语签名(在JLS中)具体指的是泛型 - 包括类型信息。
您可以使用ASM的 SignatureWriter
class。
例如,假设您希望为此方法编写签名:
public< K>你可以使用下面的代码:
$ b b $ b
SignatureWriter签名= new SignatureWriter();
signature.visitFormalTypeParameter(K);
//确保< K> extends java.lang.Object
{
SignatureVisitor classBound = signature.visitClassBound();
classBound.visitClassType(Type.getInternalName(Object.class));
classBound.visitEnd();
}
//该参数使用< K>类型变量
signature.visitParameterType()。visitTypeVariable(K);
//返回类型使用void原语('V')
signature.visitReturnType()。visitBaseType('V');
signature.visitEnd();
String signatureString = signature.toString();
相当于:
String signatureString =< K:Ljava / lang / Object;>(TK;)V;
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 to find documentation, is how to implement these using generic type information.
I am actually able to determine generic type information itself quite easily (since code will take existing fields and/or methods and full generic type handling and resolution exists). I just need to generate generics version for types that have generic type included.
I hope this is something as easy as modifying signature Asm ClassWriter/MethodVisitor calls take, but some comments in documentation indicate it might not be that easy (as generics information is stored in bit different place than regular info).
EDIT: looks like entry point is "ClassWriter.visitField/Method(...., String signature) -- note that it's "description" that contains normal non-generic class information, but term "signature" (in JLS) specifically refers to generics-including type information.
解决方案 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;"
这篇关于使用Asm字节码生成器(ClassWriter)生成具有泛型类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!