EzDevInfo.com

javaparser

Java 1.8 Parser and Abstract Syntax Tree for Java – JavaParser by javaparser

Javaparser: Visit all node types with one method

I am using Javaparser to parse Java source code.

Is there a way to implement a Visitor that can visit the abstract Node class?

I want to visit every Node and print its line number, but I don't want to implement a visit() method for every Node type (AssignExpr, BinaryExpr, IfStmt, etc...) because there are so many types.


Source: (StackOverflow)

How to Display the list of methods with signature in a java file using javaparser

I need to display the list of methods along with signature for a java class using javaparser.

I know how to display the list of methods with out signature but not along with signature. Can any one provide some examples to get methods along with signature.


Source: (StackOverflow)

Advertisements

Halstead Science Metrics

I am working in building halstead Metrics in java and I am using javaparser library and I am confusing about how I can find all java reserved words in the java imported file which will be parsing to find the operator (n1) ?


Source: (StackOverflow)

how get the fully qualified name of the java class

I have a class like below.

public class Login {
    private Keyword browser;
    private String page;
}

Keyword is a class in different package. I want to get the fully qualified name of the class Keyword while parsing the Login class using javaparser.


Source: (StackOverflow)

JavaParser - Get typed AST

I want to get typed AST from JavaParser or another parser of Java code. It means I would be able to get the type for a specific variable or parameters+returning type of a method. I googled a lot about this feature of JavaParser, but didn't find anything, I assume this is because JavaParser makes untyped AST. So, advise me how I can get this. But please don't say to parse all the code and make my own set of types, I tried and this is very hard, I think this is harder than making my own AST parser.


Source: (StackOverflow)

What is the correct way to parse variables using JavaParser?

Using JavaParser I can get a list of my methods and fields using:

//List of all methods
System.out.println("Methods: " + this.toString());
List<TypeDeclaration> types = n.getTypes();
for (TypeDeclaration type : types)
{
    List<BodyDeclaration> members = type.getMembers();
    for (BodyDeclaration member : members)
    {
        if (member instanceof MethodDeclaration)
        {
            MethodDeclaration method = (MethodDeclaration) member;
            System.out.println("Methods: " + method.getName());
        }
    }
}

//List all field variables.
System.out.println("Field Variables: " + this.toString());
List<TypeDeclaration> f_vars = n.getTypes();
for (TypeDeclaration type : f_vars)
{
    List<BodyDeclaration> members = type.getMembers();
    for (BodyDeclaration member : members)
    {
        if (member instanceof FieldDeclaration)
        {
            FieldDeclaration myType = (FieldDeclaration) member;
            List <VariableDeclarator> myFields = myType.getVariables();
            System.out.println("Fields: " + myType.getType() + ":" + myFields.toString());
        }
    }
}

But I can't figure out how to get a list of my variables. I simply want a list of all variables from a java source, regardless of scope.


Source: (StackOverflow)

How to check if a Java source file is valid (has no errors)?

In my code I open my file.java and parse him with JavaParser.

FileInputStream in = new FileInputStream(".../file.java");

        CompilationUnit cu;

        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }

........

file.java:

public class File{

     public void ownMethod(){...}

     public static void main(String[] args){

          ownMethod(5); //Note the extra parameter

     }
}

In file.java there is an error: The method main calls the method ownMethod with one parameter, but ownMethod expects 0 parameters. JavaParser doesn't detect this error and parses file.java with this error. How can I know (in my code) whether file.java has no errors? Is it posible without using a java compiler?


Source: (StackOverflow)

Counting Methods declaration + Methods Calls in a class using JavaParser

I'm trying to code rfc metric (Response for a Class), it counts the Method declarations + Method Calls.

Method declarations works fine, but I got a problem at counting method calls using JavaParser API.

Here is my code:

public class MethodPrinter {

    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("D://test.java");
        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        // visit and print the methods names
        MethodVisitor MV =new MethodVisitor();

        cu.accept(new VoidVisitorAdapter<Void>(){
            @Override
            public void visit(final MethodCallExpr n, final Void arg){
                System.out.println("method call :"+n);
                super.visit(n, arg);

            }
        }, null);
    }
}

test.java

package test;
import java.util.*;

public class ClassA 
{
  private int test;
  private ClassB classB = new ClassB();
  public void doSomething(int t){

    System.out.println ( toString());
    int i= doSomethingBasedOnClassBBV(classB.toString());
  }
  protected void doSomethingBasedOnClassB(){
    System.out.println (classB.toString());
  }
}

public class ClassB 
{
  private ClassA classA = new ClassA();
  public void doSomethingBasedOneClassA(){
    System.out.println (classA.toString());
  }

  private String toString(){
    return "classB";
  }
  private String toString(){
    return "classB";
  }
  public void doSomethingBasedOneClassA(){
    System.out.println (classA.toString());
  }
  protected void doSomethingBasedOnClassB(){
    System.out.println (classB.toString());
  }
}

the result of that code:

*method call :System.out.println(toString())

method call :toString()

method call :doSomethingBasedOnClassBBV(classB.toString())

method call :classB.toString()

method call :System.out.println(classB.toString())

method call :classB.toString()

method call :System.out.println(classA.toString())

method call :classA.toString()

method call :System.out.println(classA.toString())

method call :classA.toString()

method call :System.out.println(classB.toString())

method call :classB.toString()*

indeed, that code inspects method calls, but in my case I don't want it to count libraries method calls like System.out.println(toString()), I want it to count only toString().

If you got a better code, or another API to use... any help is welcomed, thank you in advance.


Source: (StackOverflow)

JavaParser add Generic Type as method return type

I'm using javaparser-1.0.8 and I'm trying to generate the following generic method.

public <T extends SomeInterface> T get(int param) {
  return (T) doSomeMagic(param);
}

I have the following code that is supposed to build the method:

public static void main(String[] args) throws Exception {

    // creates an input stream for the file to be parsed
    File mainActivity = new File("<path>/Main.java");
    FileInputStream in = new FileInputStream(mainActivity);

    CompilationUnit cu;
    try {
        // parse the file
        cu = JavaParser.parse(in);
        addMethod(cu);
    } finally {
        in.close();
    }

    // prints the resulting compilation unit to default system output
    System.out.println(cu.toString());
}

private static void addMethod(CompilationUnit cu) {
        WildcardType wildcardType = new japa.parser.ast.type.WildcardType(ASTHelper.createReferenceType("SomeInterface", 0));
        MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, wildcardType, "get");
        method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.PUBLIC));
        Parameter param = ASTHelper.createParameter(ASTHelper.INT_TYPE, "id");
        ASTHelper.addParameter(method, param);
        BlockStmt block = new BlockStmt();
        method.setBody(block);
        ASTHelper.addMember(cu.getTypes().get(0), method);
}

output:

public ? extends SomeInterface get(int id) {
}

Source: (StackOverflow)

Java MethodDeclaration ClassOrInterfaceDeclaration finding class names

I'm using the MethodDeclaration for a java parser that reads in source code but I'm having some problems. I can't see any methods which give me the class that this belongs to. Does a method exist for this or do I need to look in the java parser to try and create a way that will attach each MethodDeclaration to it's ClassOrInterfaceDeclaration .

I either need a way of detecting if a MethodDeclaration belongs to a class or I need a way of getting all of the methods in a ClassOrInterfaceDeclaration.

edit to make this more clear:

MethodDeclaration m = oldMethodDeclaration ; //where oldMethodDeclaration is already defined method declaration

I need a way to find the class that "m" belongs to. In the following example it will return "ClassName"

ie

    public class ClassName{
public void oldMethodDeclaration (){
}

}

Alternatively if I have

ClassOrInterfaceDeclaration ClassName;

is it possible for me to find a list of method names attached to it?


Source: (StackOverflow)

Unsure why this LOOKAHEAD is needed in these contexts

Here is my token table:

TOKEN :
{
  < A : "A" >
| < B : "B" >
| < C : "C" >
}

I have this code that contains 2 choice conflicts.

void Start() : {} {
    < A> [ Bs() ] "-" < A>
}
void Bs() : {} {
    ( "-" < B> )+
}

In order to remove the choice conflicts warning, I need to add 2 LOOKAHEAD statements like so...

void Start() : {} {
    < A> [ LOOKAHEAD(2) Bs() ] "-" < A>
}
void Bs() : {} {
    ( LOOKAHEAD(1) "-" < B> )+
}

I understand why the first LOOKAHEAD(2) is needed but I have no idea why the second LOOKAHEAD(1) is needed. Can someone please explain?

Similarly for this example...

void Start() :{} {
    one()
    |
    two()
    |
    three()
    |
    four()
}
void one() : {} {
    [ <B> ] ( <A> )* <C>
}
void two() : {} {
    <B> <A> < A> <B>
}
void three() : {} {
    <B> <B> <A> [ <B> ] <A>
}
void four() : {} {
    <A> [ <B><C> ] two()
}

In order to remove the choice conflicts, I need to add LOOKAHEADS like so...

void Start() :{} {
    LOOKAHEAD(1) one()
    |
    LOOKAHEAD(1) two()
    |
    three()
    |
    four()
}
void one() : {} {
    [ <B> ] ( <A> )* <C>
}
void two() : {} {
    <B> <A> < A> <B>
}
void three() : {} {
    <B> <B> <A> [ <B> ] <A>
}
void four() : {} {
    <A> [ LOOKAHEAD(1) <B><C> ] two()
}

I have no idea why these LOOKAHEADS remove the warnings. Any help understanding would be appreciated.


Source: (StackOverflow)

How to parse a method or any other valid expression using JavaParser

JavaParser is a java source code parsing tool. I read the documents but found it only able to parse source of a full java class, like:

public class X {
    public void show(String id) {
        Question q = Quesiton.findById(id);
        aaa.BBB.render(q);
    }
}

But I want to parse only part of it, e.g. the method declaration:

public void show(String id) {
    Question q = Quesiton.findById(id);
    aaa.BBB.render(q);
}

How to do it or is it possible? If not, is there any other tool can do this?


Update

Actually I want to parse any valid expression in java, so I can do this easily with JavaParser:

CompilationUnit unit = JavaParser.parse(codeInputStream);

addField(unit, parseField("public String name"));  // not possible now

Source: (StackOverflow)

Parsing JsonArray With JsonObject

I have some JSON with the following structure:

{
    "items":[
        {
            "product":{
                "product_id":"some",
                "price_id":"some",
                "price":"some",
                "title_fa":"some",
                "title_en":"Huawei Ascend Y300",
                "img":"some",
                "has_discount_from_price":"0",
                "discount_from_price":null,
                "type_discount_from_price":null,
                "has_discount_from_product":"0",
                "discount_from_product":null,
                "type_discount_from_product":null,
                "has_discount_from_category":"0",
                "discount_from_category":null,
                "type_discount_from_category":null,
                "has_discount_from_brand":"0",
                "discount_from_brand":null,
                "type_discount_from_brand":null,
                "weight":null,
                "features":[
                    {
                        "feature_value":"#000000",
                        "feature_id":"some",
                        "feature_title":"some"
                    },
                    {
                        "feature_value":"some",
                        "feature_id":"1652",
                        "feature_title":"some"
                    }
                ]
            },
            "number":1,
            "feature_id":"56491,56493",
            "price_inf":{
                "has_discount":0,
                "discount_type":0,
                "final_price":"400000",
                "value_discount":0
            },
            "cart_id":13
        }
    ]
}

I'm trying to access the elements "product_id" and "price_id" with the following Java code:

try{
        JSONArray feedArray=response.getJSONArray("items");
        for (int i=0;i<feedArray.length();i++){
            JSONObject feedObj=feedArray.getJSONObject(i);

            JSONObject pro=feedObj.getJSONObject("product");
            Product product = new Product();
            product.setPrice(pro.getDouble("price_id"));
            product.setTitle_fa(pro.getString("price_id"));}}

but i see product not found error.what is wrong in my parser?


Source: (StackOverflow)

How can I map java source code constructs to imports?

The wider context is that I am writing a tool which tries to rough-estimate the consultancy potential of a java developer with respect to various java libraries/technologies across projects in an organization.

The version history of a file gives me the developer who wrote/modified each line of code. If I can map java source code constructs to particular import statements(wherever relevent) I can give come up with a scoring system to assign points to developers for each usage of a java library api.


Source: (StackOverflow)

How to get class level variable declarations using javaparser ?

I want to get only the class level variable declarations. How can i get the declarations using javaparser?

public class Login {

    private Keyword browser;
    private String pageTitle = "Login";
}

Using javaparser have to get the details of variable "browser" like the type of browser is "KeyWord"


Source: (StackOverflow)