How to search for Java API methods by type signature?

后端 未结 3 1019
自闭症患者
自闭症患者 2020-12-13 04:20

Are there any open-source tools available which support searching for Java methods by the set of parameter types and return type?

As an example, say I\'m looking for

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 05:08

    Very good question although I do not understand why do you need such tool. I am sorry to say it but it seems that it takes less time to implement such tool than to write this post. Here is a code that I have just implemented. It took 182 seconds. It is a static method that takes class, return type and arguments and returns all method of the class that match the signature.

    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class ClassUtil {
        public static Method[] getMethodsBySignature(Class clazz, Class returnType, Class... args) {
            List result = new ArrayList();
            for (Method m : clazz.getDeclaredMethods()) {
                if (m.getReturnType().equals(returnType)) {
                    Class[] params = m.getParameterTypes();
                    if (Arrays.equals(params, args)) {
                        result.add(m);
                    }
                }
            }
            return result.toArray(new Method[result.size()]);
        }
    }
    

    You can spend another 5-10 minutes to implement method that opens jar, iterates over entries, calls Class.forName() and then calls my method. That's it!

提交回复
热议问题