java - 想要从类中存在的所有方法获取返回类型和参数类型

标签 java reflection

在我的代码中,我获取了类中存在的方法名称。 我想获取所有类中存在的所有方法的返回类型和参数类型。我尝试使用子字符串以及反射。但没有获得正确的输出。

对于 type-1,它仅正确地给出一种方法的输出,其余的仅给出公共(public)的输出。

对于 type-2,输出如下:

The Method Found is: public int java.lang.String.hashCode()

METHOD FOUND:public int java.lang.String.hashCode()

Return Type: int

PArams: int

PArams: int

这不是预期的输出。

我的类包含以下方法:

public int test(int a, intb)

public static String Add(String str)

public static void main(String args[])

预期输出应该是:

Method Found: public int test(int a, intb)

Return Type: int

Parameter Type: inta intb 

其余两个也一样。

任何帮助都是值得赞赏的。提前致谢。

在代码中我已注释掉//type-1 和//type-2

这是我的代码:

    package com.sify.ABCD;

        import java.io.BufferedReader;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.FileReader;
        import java.io.IOException;
        import java.lang.reflect.Method;
        import java.util.ArrayList;
        import java.util.List;


        /** Class to Recursively searching the folders, and files and 
         * the comments inside the files  
         * @param <Data>
         *
         */

        public class ABCDTool {

            String projectCode="027505";

            public static void main(String[] args) throws NoSuchMethodException {
                String parentFolder="D:/TestFileProgram";

                ABCDTool abcdTool = new ABCDTool();
                abcdTool.execute(parentFolder);

            }


            public void execute(String fileName) throws NoSuchMethodException {

                File file = new File(fileName);
                if(file.isFile()){          
                    if(file.getName().contains(".java")){
                        readFile(file);
                    }
                }
                else if (file.isDirectory()){
                    System.out.println("Analysing Directory: "+file);
                    String[] list = file.list();
                    for (String innerFile : list) {
                        execute(file+"/"+innerFile);
                    }

                }

            }

            public void readFile(File file) throws NoSuchMethodException {

                String className=null;
                String packageName=null;
                String methodName=null;
                String methodReturn=null;
                String[] methodParams=null;
                boolean packageFound=false;
                boolean classFound=false;
                boolean methodLineFound=false;
                Method method = null;
                Class classObject = null;

                try {

                    System.out.println("Reading file: "+file);

                    List<FixDetails> fileNameList = new ArrayList<FixDetails>();
                    BufferedReader bufferReader = new BufferedReader(new FileReader(file.getPath()));

                    String line="";

                    while ((line = bufferReader.readLine()) != null) {

                        int packageLength = "package ".length();
                        int classLength ="class ".length();
                        int indexOfPackage = line.indexOf("package ");
                        int indexOfClass = line.indexOf("class ");
                        int indexOfMethod = line.indexOf("public ");
                        int indexOfSemicolon= line.indexOf(";");
                        int indexOfOpenBrace = line.indexOf("(");
                        int indexOfCloseBrace = line.indexOf(")");
                        int indexOfMethodName = line.indexOf("methodName ");

                        //Finds Package Name

                        if((!packageFound) && indexOfPackage > -1) {        

                            packageName = line.substring(indexOfPackage + packageLength, indexOfSemicolon);
                            System.out.println("Package Name: " + packageName + " ");
                            packageFound=true;
                        }

                        //Finds Class Name

                        if((!classFound) && indexOfClass > -1){

                            String modified = line.substring(indexOfClass + classLength);
                            String st[] = modified.split(" ");
                            className = st[0].trim();
                            System.out.println("Class Name: " + className + " ");

                            /*Method m[] = className.getClass().getDeclaredMethods();
                            System.out.println("The Method Found is: " + m[1]);
                            for (Method method2 : m) 
                            {


                                    System.out.println("METHOD FOUND:"+method);
                                    System.out.println(method2.getReturnType());
                                    Class pr[] = method2.getParameterTypes();
                                    for (Class class1 : pr) 
                                    {
                                        System.out.println(class1);
                                    }

                                }*/
                            /*String pathName = packageName+"."+ className;
                            System.out.println("The path name is "+ pathName);
                            classObject = Class.forName(pathName);
                            Method m[] = classObject.getDeclaredMethods();
                            System.out.println("The methods present are" + m);
                            System.out.println("ClassObject:"+ classObject);*/

                            classFound = true;
                        }

                        //Finds Method Name
                        **if(indexOfMethod >-1 && indexOfOpenBrace >-1){

                            String modified = line.substring(indexOfMethod, indexOfOpenBrace);                  
                            String st[] = modified.split(" ");
                            methodName = st[st.length-1];
                            System.out.println("methodName="+methodName);
                            System.out.println("method line="+line);**
                            //Get method returnType and Params
                            if ((line !=null)) {
//Type-1
                                String str=line;
                                System.out.println("tested:"+str);
                                String[] temp = str.split(" "); 

                                for (String st1 : temp){
                                    if(st1.equalsIgnoreCase("private")||st1.equalsIgnoreCase("protected")||
                                            st1.equalsIgnoreCase("static")||st1.equalsIgnoreCase("public")||st1.equalsIgnoreCase("synchronized"))
                                    {

                                    }
                                    else {
                                        System.out.println("Return Type should be:"+st1);
                                        break;
                                    }

                                }
                                   /*for (int i =0; i < temp.length ; i++)  
                                       System.out.println("Splitted Return Type string:" +temp[i]);*/
        //Type-2
                                Method m[] = className.getClass().getDeclaredMethods();
                                System.out.println("The Method Found is: " + m[0]);
                                for (Method method2 : m) 
                                {


                                        System.out.println("METHOD FOUND:"+method);
                                        System.out.println("Return Type: "+method2.getReturnType());
                                        Class pr[] = method2.getParameterTypes();
                                        for (Class class1 : pr) 
                                        {
                                            System.out.println("PArams: "+class1);
                                        }

                                    }
                                String paramList=line.substring(indexOfOpenBrace+1, indexOfCloseBrace);
                                System.out.println("Present Params are:" + paramList);
                                methodParams=paramList.split(",");
                                for (int i =0; i < methodParams.length ; i++)  
                                       System.out.println("Splitted Paramstring:" +methodParams[i]);
                                /*
                                String returnTypeStore[] = str.split(" ");
                                methodReturn = returnTypeStore[returnTypeStore.length-1];
                                System.out.println("Method Return Type:" + methodReturn);*/


                            }
                            else System.out.println("Methodname not found");
                            methodLineFound=true;
                        }

                        if(line.contains(this.projectCode)){
                            System.out.println("Found:"+line);
                            //System.out.println("methodName="+methodName);
                            if(classFound){
                            // create FixDetails object.
                            FixDetails fixDetails = new FixDetails(packageName, className, methodName);

                            // set all required params.

                            /*fixDetails.setPackageName(packageName);
                            fixDetails.setClassName(className);
                            fixDetails.setMethodName(methodName);*/

                            System.out.println("fixDetails:" + fixDetails);
                            }else{System.out.println("Class not found yet.");}
                        }

                    }

                    bufferReader.close();

                }
                catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } /*catch (NoSuchMethodException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }*/ 

            }

            public Method getMethod(Class classObject, String line, String methodName) throws SecurityException, NoSuchMethodException {
                // TODO Auto-generated method stub

                System.out.println("Trying to search "+methodName +" in class "+classObject);
                System.out.println("line="+line);
                /*Class[] cArg = new Class[1];
                cArg[0] = int.class;
                Method m1= classObject.getClass().getDeclaredMethod(methodName, cArg );
                return m1;*/ return null;
            }



        }

最佳答案

您可以使用.class.getMethods()获取类的所有方法(也返回扩展类的方法)

Method[] methods = ABCTool.class.getMethods();

注意您可以在方法上调用的 .getName() (方法名称)、.getReturnType() 和 .getParameterTypes()

示例

public class ABCDTool {

    public String method1(String param) {
        return "Working";
    }

    public static void main(String[] args) {
        Method[] methods = ABCDTool.class.getMethods();
        for(Method method : methods){
            System.out.println("Method Found: " + method.getName());
            System.out.println("Return type: " + method.getReturnType().getName());

            Object[] params = method.getParameterTypes();
            for(Object param : params) {
                System.out.println("Parameter Type: " + param);
            }
            System.out.println();
        }
    }

}

请注意,如果您不想使用 Object 中的“wait”、“notify”和“notifyall”方法,则需要添加一些逻辑来排除它们(.getName().equals(“wait”))

关于java - 想要从类中存在的所有方法获取返回类型和参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22551556/

相关文章:

c# - 反射(reflection)继承的私有(private)方法

Java 反射 : create a instance using params from a treemap like python

c# - 使用动态是否被认为是一种不好的做法?

java - 从 Java 到 C# - 泛型转换为 BaseClass

java - Struts2 + spring Autowiring 操作的名称而不暴露某些属性

java - 如何使一台 PC 上的 Oracle 11g 数据库可供另一台 PC 使用

java - 如何在 LDAP 目录服务器模式中定义对象类 o 和 ou?

c# - 有没有办法通过反射设置 C# 只读自动实现的属性?

java - 将 JSON 保存到文件时出现编码问题,如何另存为 UTF-8?

c#通过字符串访问对象实例