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

时光毁灭记忆、已成空白 提交于 2019-12-03 11:52:32

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;"

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!