从.java文件获取方法作为文件

问题描述

我在文件夹中有一个.java文件。我想将所有方法和每个方法作为单独的文件获取。

class Foo{
public void add(int a,int b){ System.out.println(a+b);}
private int sub(int a,int b,int c){ return a-b;}}

在我的程序中,我想获取所有方法add,sub作为单独的两个文件。我对.class文件知道这一点。我们可以使用Reflection来实现,但是.java文件可能吗?

解决方法

@SanzidaSultana,我提供了从类中提取方法的代码...这使用正则表达式从类文件中提取方法。但是,该实现具有局限性。无论如何,它将帮助您解决问题。我只是在下面提供代码(带有示例)。

我提供的解析器,非常易于使用。您只需要JavaMethodParser类。只需使用它来提取方法(以它的名字!)。见下文:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Note: it is very simple parser
 *       as simple as possible
 *       it's assuming Foo.java is correctly written
 *       it can only track a few errors in Foo.java
 *       is not written in proper format
 *       so,keep that in mind
 *
 *
*/

class JavaMethodParser {
    private List<String> methodList;
    private List<String> methodNameList;
    private int cnt;
    
    public JavaMethodParser(String classContents) {
        Pattern classPattern = Pattern.compile("[a-zA-Z]*\\s*class\\s+([_a-zA-Z]+)\\s*\\{(.*)}$",Pattern.DOTALL);
        
        // now match
        Matcher classMatcher = classPattern.matcher(classContents);

        if(classMatcher.find()) {
            String methodContents = classMatcher.group(2);

            // now parse the methods
            Pattern methodPattern = Pattern.compile("[a-zA-Z]*\\s*[a-zA-Z]+\\s+([_a-zA-Z]+)\\s*?\\(.*?\\)\\s*?\\{",Pattern.DOTALL);

            Matcher methodMatcher = methodPattern.matcher(methodContents);

            List<String> methodStartList = new ArrayList<>();

            // creating method list and methodName list
            methodList = new ArrayList<>();
            methodNameList = new ArrayList<>();

            while(methodMatcher.find()) {
                String methodName = methodMatcher.group(1);
                String methodStart = methodMatcher.group();
                methodStartList.add(methodStart);
                methodNameList.add(methodName);
            }

            // reversing,cause it'll be easier to split
            // methods from the end of methodContents
            Collections.reverse(methodStartList);
            Collections.reverse(methodNameList);
            
            String buf = methodContents;
            int i=0;
            for(String methodStart: methodStartList) {
                String[] t = buf.split(Pattern.quote(methodStart));
                String method = methodStart + t[1];
                
                methodList.add(method);
                
                buf = t[0];
                i++;
            }
        } else {
            System.out.println("error: class not found");
            // throw error,cause not even a class
            // or do whatever you think necessary
        }

        // initializing cnt
        cnt = -1;
    }
    public boolean hasMoreMethods() {
        cnt += 1; // cause,cnt is initialized with -1
        return cnt < methodList.size();
    }
    public String getMethodName() {
        return methodNameList.get(cnt);
    }
    public String getMethod() {
        return methodList.get(cnt);
    }
    public int countMethods() {
        return methodList.size();
    }
}

public class SOTest {
    public static void main(String[] args) {
        try {
            Scanner in = new Scanner(new File("Foo.java"));
            String classContents = in.useDelimiter("\\Z").next().trim();

            JavaMethodParser jmp = new JavaMethodParser(classContents);

            while(jmp.hasMoreMethods()) {
                System.out.println("name: " + jmp.getMethodName());
                System.out.println("definition:\n" + jmp.getMethod());
                System.out.println();
            }

            in.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

该程序的输入为 Foo.java ,其编写方式如下:

public class Foo {
    
    private int u,v;
    private String x;
    
    public int add(int a,int b) {
        if(a + b < 0) {
            return 0;
        }
        return a + b;
    }
    
    public int sub(int a,int b) {
        return a - b;
    }
}

输出为:

name: sub
definition:
public int sub(int a,int b) {
                return a - b;
        }


name: add
definition:
public int add(int a,int b) {
                if(a + b < 0) {
                        return 0;
                }
                return a + b;
        }

我想,您知道如何使用Java在文件中写入内容。所以,我会把那部分留给你...

[P.S。]:如果您不清楚任何事情,请在评论部分告诉我...如果还不能解决问题,还请提供反馈...

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...