-4

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 .

Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
Derek Parker
  • 541
  • 2
  • 5
  • 15

2 Answers2

4

Use Class#getMethods:

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class 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]);
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • `clazz`? :-)...English answer should end with an English code... – Yair Nevet Jun 06 '14 at 15:54
  • @YairNevet it's not the first time I've seen `clazz`. You can check [`ClassUtils` source](http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-core/2.5.6/org/springframework/util/ClassUtils.java) from Spring :). – Luiggi Mendoza Jun 06 '14 at 16:00
  • Now it is more clear: [http://stackoverflow.com/a/2530174/952310](http://stackoverflow.com/a/2530174/952310) – Yair Nevet Jun 06 '14 at 16:02
  • @YairNevet see? There's no problem to avoid the rule in very specific cases like this. Apart of that, the rest of the code is wrote in proper English (I think). – Luiggi Mendoza Jun 06 '14 at 16:03
2

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);
}
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108