I am pretty new for java.I am trying to make a project that get class names,field names from desired .java file(HelloOOPP.java). I get class names successfully but i have a problem on field names.
It returns following text instead of HelloOOPP class field names(Output)(I expected to get x and y fields):
Class name:HelloOOPP
Fields:
NODE_BY_BEGIN_POSITION
ABSOLUTE_BEGIN_LINE
ABSOLUTE_END_LINE
SYMBOL_RESOLVER_KEY
App.java File:
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 File:
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 file:
public class HelloOOPP
{
public int x;
public int y;
}