Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

JNI Signature for Java Method

4.89/5 (2 votes)
15 Sep 2016CPOL 16.9K  
How to build the JNI signature for a Java method

Introduction

This code snippet is useful to build the JNI signature from a java.lang.reflect.Method.

Background

I'm currently working with JDI for a project and I need to search for the JDI counterpart of Java methods.

Interested API is ReferenceType.methodsByName(String name, String signature), but it works with JDI signature.

I haven't found anything on the web to build a JNI signature without using a bytecode manipulator library, so I decided to write it by myself.

Using the Code

The code is pretty easy to use.

Once you have in your hand a java.lang.reflect.Method object, just call JNIUtil.getJNIMethodSignature() passing your method variable.

/**    Commodity utility for JNI
 */
final class JNIUtil
{
    private static final Map<Object, String> PRIMITIVE_SIGNATURES = new HashMap<>();
    static
    {
        PRIMITIVE_SIGNATURES.put(boolean.class, "Z");
        PRIMITIVE_SIGNATURES.put(byte.class, "B");
        PRIMITIVE_SIGNATURES.put(char.class, "C");
        PRIMITIVE_SIGNATURES.put(double.class, "D");
        PRIMITIVE_SIGNATURES.put(float.class, "F");
        PRIMITIVE_SIGNATURES.put(int.class, "I");
        PRIMITIVE_SIGNATURES.put(long.class, "J");
        PRIMITIVE_SIGNATURES.put(short.class, "S");
        PRIMITIVE_SIGNATURES.put(void.class, "V");
    }
    
    private JNIUtil()    {}
        
    /**    Build JNI signature for a method
     * @param m
     * @return
     */
    public static final String getJNIMethodSignature(Method m)
    {
        final StringBuilder sb = new StringBuilder("(");
        for(final Class<?> p : m.getParameterTypes())
        {
            sb.append(getJNIClassSignature(p));
        }
        sb.append(')').append(getJNIClassSignature(m.getReturnType()));
        return sb.toString();
    }

    /**    Build JNI signature from a class
     * @param c
     * @return
     */
    static String getJNIClassSignature(Class<?> c)
    {
        if(c.isArray())
        {
            final Class<?> ct = c.getComponentType();
            return '[' + getJNIClassSignature(ct);
        }
        else if(c.isPrimitive())
        {
            return PRIMITIVE_SIGNATURES.get(c);
        }
        else
        {
            return 'L' + c.getName().replace('.', '/') + ';';
        }        
    }
}

External References

Java VM Type Signatures are available here.

History

  • 15.09.2016 - First release
  • 15.09.2016 - Added 'External references'

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)