How to generate method signature?

alex2k8 picture alex2k8 · Dec 16, 2010 · Viewed 8.5k times · Source

Desired output examples:

(Lorg/w3c/dom/Node;)Lorg/w3c/dom/Node;
(Ljava/lang/String;)Lorg/w3c/dom/Attr;

Such signatures can be generated using javap utility:

javap -s -p org.w3c.dom.Node

But is there any way to generate them programmatically. I dont' want to manually code all the rules from jni specification.

Answer

Tomáš Záluský picture Tomáš Záluský · Mar 4, 2012

http://asm.ow2.org/asm31/javadoc/user/org/objectweb/asm/Type.html#getMethodDescriptor%28java.lang.reflect.Method%29 provides exactly the result what you expect.

Offtopic note for the sake of completeness: In my use case I needed also conversion vice-versa. This can be achieved by methods Type.getArgumentTypes(sig) and Type.getReturnType(sig). Resulting array elements of type Type provide method getClassName() from which you obtain reference class via Class.forName or primitive class via simple if statement or map.