-2
class MethodFinder {

    public static String findMethod(String methodName, String[] classNames) {
            for(String cn: classNames){
                if(cn.getMethods() == methodName){
                    return methodName.getName();
                }
            }
    }
}

Implement a method that is will find the class of the provided method by its name. This method accepts two arguments, the name of the method and an array of class names, where:

methodName is the fully-qualified name of the method that needs to be found;

classNames contains one class that has the method with the given name.

It should return the fully-qualified name of the class that has the method with the given name.

For example, the method name is abs and possible classes are String, StringBuffer and Math.

String and StringBuffer have no method with the name abs. So they are not the class we are looking for. Math class has a method with the name abs. The method should return the fully-qualified name of Math class, java.lang.Math in this case.

Dhoni7
  • 15
  • 1
  • 4
  • I do not understand the question. You have an array of class names, are those fully qualified? Not sure cd.getMethods() does something. – Pavel Polivka Jul 23 '20 at 07:31
  • Can you provide a [mre] with proper input and expected output? In addition the code you've shown doesn't even compile. Also please explain to us where and with what you're having problems with – Lino Jul 23 '20 at 07:33
  • For reflection we use `Class` object getMethods(). I think the second parameter should be `Class[] classnames` – Rohan Sharma Jul 23 '20 at 07:34

1 Answers1

0

If you cant limit to just default java classes (java.lang package, which is imported implicitly)

public static String findMethod(String methodName, String[] classNames) {
    for(String cn: classNames){
        try {
            Class<?> clazz = Class.forName("java.lang." + cn);
            for (Method method : clazz.getMethods()) {
                if (method.getName().equals(methodName)) {
                    return clazz.getName();
                }
            }
        } catch(ClassNotFoundException ex) {
            // ignore
        }
    }
    return null;
}

otherwise you would have to search everything on classpath: Get all of the Classes in the Classpath

because there might be a class in.your.face.StringBuffer with a method abs()

RGL
  • 1
  • "classNames contains one class that has the method with the given name." ?? classNames should be fully qualified names - without package name, it is not clear where to look – RGL Jul 23 '20 at 17:14