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.
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() {}
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();
}
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'