Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate method signature?

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.

like image 355
alex2k8 Avatar asked Dec 16 '10 02:12

alex2k8


People also ask

How do you write a signature for a method?

The signature of a method consists of the name of the method and the description (i.e., type, number, and position) of its parameters. Example: toUpperCase() println(String s)

What is a method signature in code?

A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types. a return value and type. exceptions that might be thrown or passed back.

Which is valid method signature?

9. Which three are valid method signatures in an interface? private int getArea(); public float getVol(float x);

What are the three parts of a method signature?

The only required elements of a method signature are the method's return type, the method name, parentheses for the parameter list (which can be empty), and the method body inside curly braces (which can also be empty).


2 Answers

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.

like image 139
Tomáš Záluský Avatar answered Oct 11 '22 17:10

Tomáš Záluský


I generate like this:

private static String calculateMethodSignature(Method method){
        String signature = "";
        if(method != null){
            signature += "(";
            for(Class<?> c:method.getParameterTypes()){
                String Lsig = Array.newInstance(c,1).getClass().getName();
                signature += Lsig.substring(1);
            }
            signature += ")";

            Class<?> returnType = method.getReturnType();
            if(returnType == void.class){
                signature += "V";
            }else{
                signature += Array.newInstance(returnType,1).getClass().getName();
            }

            signature = signature.replace('.','/');
        }

        return signature;
    }
like image 26
Summer Avatar answered Oct 11 '22 17:10

Summer