gpt4 book ai didi

java - 如何在类中搜索重载方法

转载 作者:行者123 更新时间:2023-11-30 08:08:36 25 4
gpt4 key购买 nike

有没有一种简单的方法可以在java项目中搜索类中的哪些方法具有相同的“名称”?

例如:

public class Banana{

void findBananas(Ananas ananas) { --- }

void findBananas(Bananas banana) { --- }

void findCiao(Ciao ciao) { --- }

void findCiao2(Ciao ciao) { --- }

}

搜索必须指定在 Banana 类中重复方法名称“findBananas”。

任何工具/IDE表示赞赏。

最佳答案

已更新帖子。旧版本已删除

您可以使用反射。我不知道你的确切需求,但这个非常适合我的项目,这里是 git test project :

为此,您需要使用“org.reflections:reflections:0.9.10”库。可以从这里下载https://code.google.com/p/reflections/

public static class MethodInfo {
Class fromClass;
ArrayList<Method> methods = new ArrayList<Method>();

public MethodInfo(Class fromClass) {
this.fromClass = fromClass;
}
}

public static HashMap<String, MethodInfo>
findOverloadedMethods(String packageToScan, boolean declaredInClass){

Set<Class<?>> allClasses = findAllClassesInPackage(packageToScan);
System.out.println("Number of Classes in "+ packageToScan
+" = " + allClasses.size());

HashMap<String, MethodInfo> map = new HashMap<String, MethodInfo>();

for (Class c : allClasses) {
try {
findAllMethodsForClass(c, declaredInClass, map);
}catch (java.lang.NoClassDefFoundError e){
//have no idea why some classes throw this NoClassDefFoundError
System.err.println(c.getName() + ": java.lang.NoClassDefFoundError");
}
}

return map;
}
public static void findAllMethodsForClass(Class c, boolean declaredInClass,
HashMap<String, MethodInfo> map)
throws java.lang.NoClassDefFoundError{
//Set<Method> methods = ReflectionUtils.getAllMethods(c);
Method[] methods = declaredInClass ? c.getDeclaredMethods(): c.getMethods();

for (Method method : methods) {
String key = c.getName() + "." + method.getName();

if (!map.containsKey(key)) {
map.put(key, new MethodInfo(c));
}

MethodInfo methodInfo = map.get(key);
methodInfo.methods.add(method);
}
}
public static Set<Class<?>> findAllClassesInPackage(String packageToScan){
Reflections reflections = new Reflections(
new SubTypesScanner(false), new ResourcesScanner(),
new FilterBuilder().include(FilterBuilder.prefix(packageToScan)));

return reflections.getSubTypesOf(Object.class);
}

public static void print(HashMap<String, RScanner.MethodInfo> map){
for (String key : map.keySet()) {
RScanner.MethodInfo info = map.get(key);
if (info.methods.size() > 1) {
// wait method has 3 overloads in Object class
if (!info.methods.get(0).getName().equals("wait"))
System.out.println(key + " : " + info.methods.size());
}
}
}

关于java - 如何在类中搜索重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com