我是java的新手。我正在尝试创建一个项目,从所需的.java文件(HelloOOPP.java)获取类名,字段名。 我成功获得了类名,但我对字段名称有疑问。
它返回以下文本而不是HelloOOPP类字段名称(输出)(我希望得到x和y字段):
Class name:HelloOOPP
Fields:
NODE_BY_BEGIN_POSITION
ABSOLUTE_BEGIN_LINE
ABSOLUTE_END_LINE
SYMBOL_RESOLVER_KEY
App.java文件:
package com.app;
import java.io.File;
import java.io.FileNotFoundException;
public class App
{
public static void main(String[] args) throws FileNotFoundException {
System.out.println(GetTypes.parseClassname(new File("C:\\HelloOOPP.java")));
}
}
GetTypes.java文件:
package com.app;
import com.github.javaparser.*;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.*;
import java.io.*;
import java.lang.reflect.Field;
public class GetTypes {
public static String parseClassname(File filename) throws FileNotFoundException {
FileInputStream fin = new FileInputStream(filename);
CompilationUnit cu = JavaParser.parse(fin);
StringBuilder build=new StringBuilder();
for (TypeDeclaration type : cu.getTypes())
{
if (type.isClassOrInterfaceDeclaration())
{
build.append("Class name:");
build.append(type.getName());
build.append("\n");
build.append("Fields:");
build.append("\n");
build.append(Get_Fields(type));
}
}
return build.toString();
}
private static StringBuilder Get_Fields(TypeDeclaration c) //Get all field names
{
Field[] fields = c.getClass().getFields();
StringBuilder str=new StringBuilder();
for(int i=0;i<fields.length;i++)
{
str.append(fields[i].getName());
str.append("\n");
}
return str;
}
/*
private int Count_Fields(TypeDeclaration c)
{
}*/
}
HelloOOPP.java文件:
public class HelloOOPP
{
public int x;
public int y;
}
答案 0 :(得分:1)
你正在混合使用Javaparser和经典反射。
写作时
Field[] fields = c.getClass().getFields();
,你得到的是TypeDeclaration类的字段,而不是HelloOOPP
类(这就是为什么你会看到ABSOLUTE_BEGIN_LINE
等意外的字段名称。)
根据问题How to get class level variable declarations using javaparser ? ,您的方法可能如下所示:
private static StringBuilder Get_Fields(TypeDeclaration c) //Get all field names
{
List<BodyDeclaration> members = c.getMembers();
StringBuilder str=new StringBuilder();
if(members != null) {
for (BodyDeclaration member : members) {
//Check just members that are FieldDeclarations
FieldDeclaration field = (FieldDeclaration) member;
str.append(field.getVariables().get(0).getId().getName());
str.append("\n");
}
}
return str;
}