英文:
Fully qualified name of a class?
问题
class MethodFinder {
public static String findMethod(String methodName, String[] classNames) {
for (String cn : classNames) {
try {
Class<?> clazz = Class.forName(cn);
for (java.lang.reflect.Method method : clazz.getMethods()) {
if (method.getName().equals(methodName)) {
return clazz.getName();
}
}
} catch (ClassNotFoundException e) {
// Handle the exception if the class is not found
}
}
return null; // Return null if no matching class is found
}
}
英文:
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.
答案1
得分: 0
如果您无法仅限于默认的Java类(隐式导入的java.lang包):
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) {
// 忽略
}
}
return null;
}
否则,您将不得不在类路径上搜索所有内容:https://stackoverflow.com/questions/3222638/get-all-of-the-classes-in-the-classpath
因为可能会有一个名为in.your.face.StringBuffer
的类,其中有一个abs()
方法。
<details>
<summary>英文:</summary>
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: https://stackoverflow.com/questions/3222638/get-all-of-the-classes-in-the-classpath
because there might be a class in.your.face.StringBuffer with a method abs()
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论