Search code examples
javajvmbytecode

What's the method-type of JVM type signature


According to the JVM Specification, there are 11 type signatures of JVM, one of them is 'method type', i never see it. what is it ?


Solution

  • As Holger points out, the document you link to is for the Java Native Interface (JNI), not the JVM specification.

    The method signature is used by JNI to determine (more precisely resolve) which method to use. As the document points out, this is the same approach used by the JVM.

    A method signature allows a method to be uniquely identified. The Java language has the concept of method overloading, meaning you can have multiple methods in a class with the same name. How the compiler distinguishes between them is using the method signature, which consists of the method's name, generic type parameters (if any) and the number and type of its arguments. It's important to understand that only these values are used for the signature. Several other aspects of the method's definition are not considered:

    • Return type
    • Thrown exceptions
    • Whether this is a static or instance method
    • The access modifier (public, package, protected, private)

    This means you can't have two methods with the same name which have the same number and types of arguments even if the return type differs or throw different exceptions. (See section 8.4.2 of the Java Language Specification for more detail).

    However, inside the JVM, the method signature does include the return type (see section 4.3.3 of the Java Virtual Machine Specification for more detail).

    In JNI, the method signature is defined using the syntax on the page you link to.

    Let's use the example method on that page:

    long f (int n, String s, int[] arr) { ... }
    

    The JVM representation of that would be

    (ILjava/lang/String;[I)J 
    

    To use that in JNI we might have something like this:

    jclass cls = (*env)->GetObjectClass(env, obj);
    jmethodID mid = (*env)->GetMethodID(env, cls, "f", "(ILjava/lang/String;[I)J");
    

    As you can see, we pass the method type signature as a parameter to the GetMethodID method so JNI (and the JVM) can resolve which method to return the identity for.