-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 .

4
  • 6
    Look into reflection. Commented Jun 6, 2014 at 15:47
  • 1
    Why don't you google it before posting a question. Commented Jun 6, 2014 at 15:50
  • 1
    Down-vote from me. This is trivially Google-able. Commented Jun 6, 2014 at 15:50
  • 2
    @DerekParker I searched for the phrase "java list public methods". Perhaps I'm a Google wizard in comparison to you, but I suspect not. Commented Jun 6, 2014 at 15:53

2 Answers 2

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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

clazz? :-)...English answer should end with an English code...
@YairNevet it's not the first time I've seen clazz. You can check ClassUtils source from Spring :).
@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).
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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.