Skip to content

Instantly share code, notes, and snippets.

@Miouyouyou
Created December 16, 2017 22:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Get the signatures of functions declared in Java Class, at runtime, using Java.lang.reflect methods
package your.package.name;
import java.lang.reflect.Method;
import java.util.HashMap;
import android.util.Log;
public class MethodsHelpers {
static public HashMap<Class, String> primitive_types_codes;
static public String LOG_TAG = "MY_APP";
static {
primitive_types_codes = new HashMap<Class,String>();
primitive_types_codes.put(void.class, "V");
primitive_types_codes.put(boolean.class, "Z");
primitive_types_codes.put(byte.class, "B");
primitive_types_codes.put(short.class, "S");
primitive_types_codes.put(char.class, "C");
primitive_types_codes.put(int.class, "I");
primitive_types_codes.put(long.class, "J");
primitive_types_codes.put(float.class, "F");
primitive_types_codes.put(double.class, "D");
}
public static String code_of(final Class class_object) {
final StringBuilder class_name_builder = new StringBuilder(20);
Class component_class = class_object;
while (component_class.isArray()) {
class_name_builder.append("[");
component_class = component_class.getComponentType();
}
if (component_class.isPrimitive())
class_name_builder.append(primitive_types_codes.get(component_class));
else {
class_name_builder.append("L");
class_name_builder.append(
component_class.getCanonicalName().replace(".", "/")
);
class_name_builder.append(";");
}
return class_name_builder.toString();
}
public static void print_methods_descriptors_of(Class analysed_class) {
StringBuilder descriptor_builder = new StringBuilder(32);
Method[] methods = analysed_class.getDeclaredMethods();
for (Method meth : methods) {
descriptor_builder.append("(");
for (Class param_class : meth.getParameterTypes())
descriptor_builder.append(code_of(param_class));
descriptor_builder.append(")");
descriptor_builder.append(code_of(meth.getReturnType()));
Log.d(LOG_TAG,
String.format("%s\n"+
"Name : %s\n"+
"Descriptor : %s\n\n",
meth.toString(),
meth.getName(),
descriptor_builder.toString())
);
descriptor_builder.delete(0, descriptor_builder.length());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment