Last active
June 12, 2019 16:21
-
-
Save alwarren/23d06f896708b3e7cb89cabc9af31df0 to your computer and use it in GitHub Desktop.
A generic class to retrive public methods and their names from a class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Method; | |
import java.lang.reflect.Modifier; | |
import java.util.ArrayList; | |
import java.util.List; | |
import static java.lang.System.out; | |
public class Spy { | |
public static List<Method> publicMethods(Class<?> clazz) { | |
List<Method> results = new ArrayList<>(); | |
Method[] methods = clazz.getDeclaredMethods(); | |
for (Method method : methods) { | |
if (!method.isSynthetic()) { | |
int modifiers = method.getModifiers(); | |
if ((modifiers & Modifier.PUBLIC) == Modifier.PUBLIC) { | |
results.add(method); | |
} | |
} | |
} | |
return results; | |
} | |
public static List<String> publicMethodNames(Class<?> clazz) { | |
List<String> results = new ArrayList<>(); | |
List<Method> methods = publicMethods(clazz); | |
for (Method method : methods) results.add(method.getName()); | |
return results; | |
} | |
private static int modifierFromString(String s) { | |
int m = 0x0; | |
if ("public".equals(s)) m |= Modifier.PUBLIC; | |
else if ("protected".equals(s)) m |= Modifier.PROTECTED; | |
else if ("private".equals(s)) m |= Modifier.PRIVATE; | |
else if ("static".equals(s)) m |= Modifier.STATIC; | |
else if ("final".equals(s)) m |= Modifier.FINAL; | |
else if ("transient".equals(s)) m |= Modifier.TRANSIENT; | |
else if ("volatile".equals(s)) m |= Modifier.VOLATILE; | |
return m; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment