首页 > 解决方案 > 如何从Java文件中获取变量名列表?

问题描述

如何从 Java 文件中获取变量列表?到目前为止,我已经开始阅读文件并使用空格分隔每个单词。不幸的是,这将返回所有导入语句、注释..等

public ArrayList<String> getVariables(String javaFilePath) {
    ArrayList<String> variableList = new ArrayList<String>();
    BufferedReader br;
    try {
        // creating a buffer reader from the file path
        br = new BufferedReader(new FileReader(new File(javaFilePath)));

        String line;
        while ((line = br.readLine()) != null) {
            String[] variables = line.split("\\s+");
            for (String variable : variables) {

                variableList.add(variable);

            }

        }

        br.close();
    } catch (FileNotFoundException e) {
        logger.error("This is FileNotFoundException error : " + e.getMessage());
    } catch (IOException e) {
        logger.error("This is IOException error : " + e.getMessage());
    }

    return variableList;
}

例如:我在 C:\Sample.java 上保存了 java 文件。它的代码如下所示:

package com.test;

import java.io.File;
import java.io.FileInputStream;

public class Sample {
String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

使用上述方法的输出返回以下内容:

package
com.test;

import
java.io.File;
import
java.io.FileInputStream;

public
class
Sample
{
String
name;

public
String
getName()
{

return
name;
}

public
void
setName(String
name)
{

this.name
=
name;
}

}

问题:如何修改上面显示的方法以便仅获取变量。例如:我只想要上述类的“名称”和“样本”。

标签: javafilevariables

解决方案


推荐阅读