希望从类中呈现的所有方法中获得返回类型和参数类型



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

对于type-1,它只正确地给出一个方法的输出,对于rest,它只给出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 () (methodname) .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"one_answers"notifyall"方法,你需要添加一些逻辑来排除它们(.getName().equals("wait"))

相关内容

  • 没有找到相关文章

最新更新