Is there an easy way of return an objects public method names as a string array?
My limited Java knowledge can only come up with using a reader and scan through the .java file .
Is there an easy way of return an objects public method names as a string array?
My limited Java knowledge can only come up with using a reader and scan through the .java file .
Use Class#getMethods
:
Returns an array containing
Method
objects reflecting all the public methods of the class or interface represented by thisClass
object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
public static List<String> getPublicMethods(Class<?> clazz) {
Method[] publicMethods = clazz.getMethods();
List<String> methodNames = new ArrayList<>();
for (Method method : publicMethods) {
methodNames.add(method.getName());
}
return methodNames;
}
If you want it strictly as an array, use the above method altogether with List#toArray
:
public static String[] getPublicMethods(Class<?> clazz) {
Method[] publicMethods = clazz.getMethods();
List<String> methodNames = new ArrayList<>();
for (Method method : publicMethods) {
methodNames.add(method.getName());
}
return methodNames.toArray(new String[publicMethods.length]);
}
Use reflection, for example:
Class aClass = MyObject.class;
Method[] methods = aClass.getMethods();
Now, you can project a string array from this array (Method[]
):
List<String> methodNames = new ArrayList<>();
for (Method method : methods) {
methodNames.add(method.getName());
}
And play with it as you wish, for example:
for (String methodName : methodNames) {
System.out.println(methodName);
}