How to get class level variable names using javaparser? - java

I was able to get class level variable's declarations using the following code. But I only need the variable name. This is the output I get for following code - [private boolean flag = true;]
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
public class CuPrinter{
public static void main(String[] args) throws Exception {
// creates an input stream for the file to be parsed
FileInputStream in = new FileInputStream("C:\\Users\\arosh\\IdeaProjects\\Bot_Twitter\\src\\MyBot.java");
CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(in);
} finally {
in.close();
}
cu.accept(new ClassVisitor(), null);
}
private static class ClassVisitor extends VoidVisitorAdapter<Void> {
#Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
/* here you can access the attributes of the method.
this method will be called for all methods in this
CompilationUnit, including inner class methods */
System.out.println(n.getFields());
super.visit(n, arg);
}
}
}

You can use the following simple regex:
final String regex = "^((private|public|protected)?\\s+)?.*\\s+(\\w+);$";
Which then can be compiled into a Pattern:
final Pattern pattern = Pattern.compile(regex);
And then finally be used in a for-loop:
for(final String field : n.getFields()){
// create a regex-matcher
final Matcher matcher = pattern.matcher(field);
// if field matches regex
if(matcher.matches()){
// get the last group -> the fieldName
final String name = matcher.group(matcher.groupCount());
System.out.println("FieldName: " + name);
}
}

You can try this. If you have more than one variables in FieldDeclarations, use one more for loop inside.
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
super.visit(n, arg);
for(FieldDeclaration ff:n.getFields())
{
System.out.println(ff.getVariable(0).getName());
}
}

Related

How to Parse static level variable from the JAVA file?

I'm trying to Parse the static variable value from the JAVA file. But couldn't be able to parse the variable.
I've used JavaParser to Parse the code and fetch the value of variable. I got success in fetching all other class level variable and value but couldn't be able to parse the static field.
The Java File looks like ...
public class ABC {
public string variable1 = "Hello How are you?";
public boolean variable2 = false;
public static String variable3;
static{
variable3 = new String("Want to Fetch this...");
}
//Can't change this file, this is input.
public static void main(String args[]){
//....Other Code
}
}
I'm able to parse the all variables value except "variabl3". The Code of Java File looks like above Java Code and I need to Parse "variable3"'s value.
I've done below code to parse the class level variable...
import java.util.HashMap;
import java.util.List;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class StaticCollector extends
VoidVisitorAdapter<HashMap<String, String>> {
#Override
public void visit(FieldDeclaration n, HashMap<String, String> arg) {
// TODO Auto-generated method stub
List <VariableDeclarator> myVars = n.getVariables();
for (VariableDeclarator vars: myVars){
vars.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
//System.out.println("Variable Name: "+vars.getNameAsString());
}
}
}
Main Method ...
public class Test {
public static void main(String[] args) {
File file = new File("filePath");
CompilationUnit compilationUnit = null;
try {
compilationUnit = JavaParser.parse(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String> collector = new HashMap<String, String>();
compilationUnit.accept(new StaticCollector(), collector);
}
}
How could I parse the value of "variable3", which is static and value assigned inside static block? There might be other variable in the code but I need to find value of particular variable value (in this case Variable3).
Am I doing something wrong or i need to add some other way, please suggest.
Inspecting the AST as something that's easily readable, e.g., a DOT (GraphViz) image with PlantUML is a huge help to solve this kind of problem. See this blog on how to generate the DOT as well as other formats.
Here's the overview, with the "variable3" nodes highlighted (I just searched for it in the .dot output and put a fill color). You'll see that there are TWO spots where it occurs:
Zooming in on the node space on the right, we can see that the second sub-tree is under an InitializerDeclaration. Further down, it's part of an AssignExpr where the value is an ObjectCreationExpr:
So, I adapted your Visitor (it's an inner class to make the module self contained) and you need to override the visit(InitializerDeclaration n... method to get to where you want:
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.InitializerDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
public class Test {
public static void main(String[] args) {
File file = new File("src/main/java/ABC.java");
CompilationUnit compilationUnit = null;
try {
compilationUnit = StaticJavaParser.parse(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String> collector = new HashMap<String, String>();
compilationUnit.accept(new StaticCollector(), collector);
}
private static class StaticCollector extends
VoidVisitorAdapter<HashMap<String, String>> {
#Override
public void visit(FieldDeclaration n, HashMap<String, String> arg) {
List<VariableDeclarator> myVars = n.getVariables();
for (VariableDeclarator vars: myVars){
vars.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
//System.out.println("Variable Name: "+vars.getNameAsString());
}
}
#Override
public void visit(InitializerDeclaration n, HashMap<String, String> arg) {
List<Statement> myStatements = n.getBody().getStatements();
for (Statement s: myStatements) {
s.ifExpressionStmt(expressionStmt -> expressionStmt.getExpression()
.ifAssignExpr(assignExpr -> System.out.println(assignExpr.getValue())));
}
}
}
}
Here's the output showing additionally variable3's initialization in the static block:
"Hello How are you?"
false
new String("Want to Fetch this...")

How to get field names in TypeDeclaration object?

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;
}
You are mixing Javaparser and classical reflection.
When you write
Field[] fields = c.getClass().getFields();
, what you get is the fields from the TypeDeclaration class, not the HelloOOPP class (that's why you see unexpected field names like ABSOLUTE_BEGIN_LINE).
Based on the question How to get class level variable declarations using javaparser ?
, your method could look like :
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;
}

How do I use value from one class for another class Calling from main method

One.java
public class One {
String asd;
public class() {
asd="2d6"
}
public static void main(String args[]) {
Two a = new Two();
}
}
Two.java
public class Two {
ArrayList<String>data;
String asd;
public Two(String asd){
this.asd=asd;
data.add(this.asd);
}
}
How do I use this asd value of second for third class calling from first class's main method.
**Third class**
Per comments of #Maroun Maroun and #Bennyz, you can create a getter and setter method in your Two class:
import java.util.ArrayList;
public class Two {
ArrayList<String> data;
String asd;
public Two(String asd) {
this.asd = asd;
data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
data.add(this.asd);
}
// Get value of 'asd',
public String getAsd() {
return asd;
}
// Set value of 'asd' to the argument given.
public void setAsd(String asd) {
this.asd = asd;
}
}
A great site to learn about this while coding (so not only reading), is CodeAcademy.
To use it in a third class, you can do this:
public class Third {
public static void main(String[] args) {
Two two = new Two("test");
String asd = two.getAsd(); //This hold now "test".
System.out.println("Value of asd: " + asd);
two.setAsd("something else"); //Set asd to "something else".
System.out.println(two.getAsd()); //Hey, it changed!
}
}
There are also some things not right about your code:
public class One {
String asd;
/**
* The name 'class' cannot be used for a method name, it is a reserved
* keyword.
* Also, this method is missing a return value.
* Last, you forgot a ";" after asd="2d6". */
public class() {
asd="2d6"
}
/** This is better. Best would be to create a setter method for this, or
* initialize 'asd' in your constructor. */
public void initializeAsd(){
asd = "2d6";
}
public static void main(String args[]) {
/**
* You haven't made a constructor without arguments.
* Either you make this in you Two class or use arguments in your call.
*/
Two a = new Two();
}
}
Per comment of #cricket_007, a better solution for the public class() method would be:
public class One {
String asd;
public One(){
asd = "2d6";
}
}
This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.

java return string from class (linkedhashmap)

Not sure if the title makes sense, but I am trying to return a Success message from a class that receives a linkedhashmap, however eclipse is giving me error when I try to compile the files, offering
Remove arguments to match 'logFile()'
Create constructor 'logFile(Map<String, String>)'
How do set it up to send a Map and revieve a String?
thx
Art
Code corrected as per #Jeff Storey below with error suppression for eclipse
calling class
eventLog.put(stringA,stringB);
logFile logStuff = new logFile();
successRtn = logFile.Process(eventLog);
// Do Stuff with SuccessRtn
logFile class
public class logFile {
static String Success = "Fail";
public static String Process(Map<String, String> eventlog){
// Do Stuff
Success = "Yeh!"
return Success;
}
public static void main(String[] args){
#SuppressWarnings("static-access")
String result = new logFile().Procces(eventLog);
System.out.println("result = " + result);
}
The main method is a special method whose signature must public static void main(String[] args) when being used as an entry point to your application. Create a second method that does the actual work, like this:
public class LogFile {
public String process(Map<String,String> eventLog) {
// do stuff
return success;
}
public void main(String[] args) {
// eventLog will probably be read from a filepath passed into the args
String result = new LogFile().process(eventLog);
System.out.println("result = " + result);
}
}
Note that a lot of your naming conventions are also non standard. Classes should begin with a capital letter and variables should begin with a lower case.

how do I pass a variable from a class that uses Scanner to the main class?

how do I get the read txt file into the main class?
//main class
public class mainClass {
public static void main(String[]args) {
load method = new load("Monster");
}
}
//scanner class
public class load {
public static void loader(String... aArgs) throws FileNotFoundException {
load parser = new load("resources/monsters/human/humanSerf.txt");
parser.processLineByLine();
log("Done.");
}
public load(String aFileName){
fFile = new File(aFileName);
}
public final void processLineByLine() throws FileNotFoundException {
//Note that FileReader is used, not File, since File is not Closeable
Scanner scanner = new Scanner(new FileReader(fFile));
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
scanner.close();
}
}
public void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Stat is : " + quote(name.trim()) + ", and the value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
}
public final File fFile;
public static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
public String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
Which method do I call from the main class and what variables do I return from that method if I want the text from the file. If anyone has a website that can help me learn scanner(got this source code of the internet and only sort of understand it from JavaPractises and the sun tutorials) that would be great. thanks
First, you probably want to follow standard Java naming conventions - use public class MainClass instead of mainClass.
Second, for your methods, the public has a specific purpose. See here and here. You generally want to label methods as public only as necessary (in jargon, this is known as encapsulation).
For your question - in the Load class, you can append all the text from the file to a String, and add a public getter method in Load which will return that when called.
Add this at the start of Load:
public class Load {
private String fileText;
// ... rest of class
And add this getter method to the Load class. Yes, you could simply mark fileText as public, but that defeats the purpose of Object-Oriented Programming.
public getFileText(String aFileName){
return fileText;
}
Finally, use this new method for log. Note that there is no need to use Object.
private static void log(String line) {
System.out.println(line);
fileText += aObject;
}
You can now get the read file into the main class by calling method.getFileText()
Code was TL;DR
If you want to get all of the data from the load class's .txt file, then you need to write a method in load to get the lines. Something like this would work:
public String[] getFileAsArray() {
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(fFile);
while(in.hasNextLine())
lines.add(in.nextLine();
String[] retArr = new String[lines.size()];
return lines.toArray(retArr);
}

Categories