0

I want to read parameters passed to a particular method of a java class. Here is the java file:

package config;

public class ABC extends LineAvailabilityNew
{

public ABC(Message msg)
    throws MessageHandlerExcection
{
    super(msg);
}

public void doMessageDataOverrides()
    throws MessageHandlerExcection
{
    super.doMessageDataOverrides();
    setWorkingLineQty("21");
    setStoppedLineQty("10");
    setworkingLineExchangeGroupCode("GOL");
    setWorkingLineWithServiceID("01014013024", "24", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", "");
    setOneMoreWorkingLineWithServiceID("01014013025", "25", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", "");
    setOneMoreWorkingLineWithServiceID("01014013026", "26", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", "");
    setOneMoreStoppedLineWithServiceID("01014013015", "15", "PSTN Single Line", "N", "N", "", "NTE", "GOL", "", "Standard", "");

}
}

Here I want parameter values supplied to setWorkingLineWithServiceID();

 So my output should be something like this:
 1> "01014013024", "24", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", ""
 2> "01014013026", "26", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", ""

I am not aware of APIs used for reading .java files from java code. Also my project constraint is to use Java 5

2
  • Can you edit setOneMoreWorkingLineWithServiceID method source code? If so, just log the input parameters or display it on standard output.
    – Benjamin
    Apr 24, 2014 at 8:03
  • As mentioned above you could just log or use System.out.println() in those methods to log the parameters. But if you looking to read a .java file (I am not sure if this is needed) ? It is same like any other text file. Check mkyong.com/java/…
    – Jay
    Apr 24, 2014 at 8:16

4 Answers 4

2

you can use javaparser

Maven dependency

<dependency>
    <groupId>com.google.code.javaparser</groupId>
    <artifactId>javaparser</artifactId>
    <version>1.0.8</version>
</dependency>

Parser:

import japa.parser.JavaParser;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.BodyDeclaration;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.body.TypeDeclaration;
import japa.parser.ast.expr.MethodCallExpr;
import japa.parser.ast.stmt.BlockStmt;
import japa.parser.ast.visitor.GenericVisitorAdapter;

import java.io.InputStream;
import java.util.List;

public class App {

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

        // creates an input stream for the file to be parsed
        InputStream in = App.class.getResourceAsStream("ABC.java");
        // if you want to use absolute path try this
        // InputStream in = FileInputStream("/path/to/file/ABC.java");


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

        // prints the resulting compilation unit to default system output
        visit(cu);
    }

    private static void visit(CompilationUnit cu) {
        List<TypeDeclaration> types = cu.getTypes();
        for (TypeDeclaration type : types) {
            List<BodyDeclaration> members = type.getMembers();
            for (BodyDeclaration member : members) {
                if (member instanceof MethodDeclaration) {
                    MethodDeclaration method = (MethodDeclaration) member;
                    if ("doMessageDataOverrides".equals(method.getName())) {
                        BlockStmt body = method.getBody();
                        body.accept(new MyVisitor(), null);
                    }
                }
            }
        }
    }

    private static class MyVisitor extends GenericVisitorAdapter {
        public Object visit(MethodCallExpr n, Object arg) {
            if ("setOneMoreWorkingLineWithServiceID".equals(n.getName())){
                System.out.println(n.getArgs());
            }
            return super.visit(n, arg);
        }
    }

}

Output:

--- UPDATE ---

Project files:

1) This is a maven project. So ABC.java file should be in src/main/resources folder. if you want to use absolute path then try with FileInputStream as below.

InputStream in = FileInputStream("/path/to/file/ABC.java");

2) n.getArgs() is a java.util.List. you can get per argument. Try this new MyVisitor.

private static class MyVisitor extends GenericVisitorAdapter {
    public Object visit(MethodCallExpr n, Object arg) {
        if ("setOneMoreWorkingLineWithServiceID".equals(n.getName())){
            for (Expression expression : n.getArgs()) {
                System.out.println(expression.toString());
            }
        }
        return super.visit(n, arg);
    }
}
1
  • Your piece of code seems quite interesting to work on. But 2 queries on this: 1> I tried your code but InputStream object is throwing NullPointerException. My ABC.java file is located on different path as of my project but I am passing the absolute path of the file to the function. 2> I want to make use of the output value i.e. instead of displaying it through System.out, I want to pass the value to calling function. How can this be achieved?
    – Neha S
    Apr 24, 2014 at 9:33
0

Since you said "I am not aware of APIs used for reading .java files from java code" I am going to assume that you are after the values that methods in ABC.java are passing to setOneMoreWorkingLineWithServiceID as opposed to logging all values passed to setOneMoreWorkingLineWithServiceID by other programs as well.

If that is the case, you can use the standard way of reading any file in java. The following links provide enough information to get you started:

Java: How to read a text file

http://alvinalexander.com/blog/post/java/how-open-read-file-java-string-array-list

Once the File is open and read into a string, you can parse the line that contains the calls into setOneMoreWorkingLineWithServiceID and read the values.

0

Let me post you a simple coding to achieve your goal:

Please note that:

  • I assumed that your .java file was saved under the name Demo.java
  • Please note that the coding below is written only with the intention to achieve SO's objective in a simple manner.
import java.io.*;

public class FileRead 
{

  public static int findString(String str, String findStr)
  {
    int lastIndex = 0;
    int count =0;

    while(lastIndex != -1)
    {
       lastIndex = str.indexOf(findStr,lastIndex);

       if( lastIndex != -1)
       {
         count ++;
         lastIndex+=findStr.length();
       }
    }
    return count;
  }

    public static void main(String args[]) throws IOException
    {
        BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
        System.out.print("Enter the name function to be searched for: ");
        String my_fun = in.readLine();

        FileReader fileReader = new FileReader(new File("Demo.java"));
        BufferedReader br = new BufferedReader(fileReader);

        String line = null;

        while ((line = br.readLine()) != null) 
        {
            if(findString(line, my_fun)>0)
            {
              int startIndex = line.indexOf("(");
              int endIndex = line.indexOf(")");
              String finalString = line.substring(startIndex+1,endIndex);
              System.out.println(finalString);
            }
        }
        in.close();
    }
    }

The output for the program shown above will be as follows:

C:\stackOverflowUser\myCode>javac FileRead.java C:\stackOverflowUser\myCode>java FileRead Enter the name function to be searched for: setOneMoreWorkingLineWithServiceID "01014013025", "25", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", "" "01014013026", "26", "MPF", "N", "N", "A line in e2e", "", "NTE", "GOL", "", "Standard", ""
1
  • Even I am going with almost similar kind of approach for now but I wanted to know is there any Parser class or API available so that it can be done with an ease and also will get to know something new. ;)
    – Neha S
    Apr 24, 2014 at 9:25
0

Thanks bhdrk

I modified your code a bit to suit my requirement and it worked. Thanks :)

Here's the file:

package test;

import japa.parser.JavaParser;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.BodyDeclaration;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.body.TypeDeclaration;
import japa.parser.ast.expr.Expression;
import japa.parser.ast.expr.MethodCallExpr;
import japa.parser.ast.stmt.BlockStmt;
import japa.parser.ast.visitor.GenericVisitorAdapter;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class JavaFileParser {

static String strFilePath = null;
static String strMainMethod = null;
static String strMethodName = null; 

private static void dataSetter(String pFilePath, String pMainMethod, String pMethodName) {
    strFilePath = pFilePath;
    strMainMethod = pMainMethod;
    strMethodName = pMethodName;
}

public static ArrayList getMethodParameters(String pFilePath, String pMainMethod, String pMethodName) throws Exception {


    // creates an input stream for the file to be parsed
    ArrayList args1 =  null;

    dataSetter(pFilePath,pMainMethod, pMethodName);
    InputStream in = new FileInputStream(strFilePath);

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

    // prints the resulting compilation unit to default system output
    args1 =  visit(cu);     

    return args1;
}

private static ArrayList visit(CompilationUnit cu) {
    ArrayList  paramatersList = null;
    List<TypeDeclaration> types = cu.getTypes();
    for (TypeDeclaration type : types) {
        List<BodyDeclaration> members = type.getMembers();
        for (BodyDeclaration member : members) {
            if (member instanceof MethodDeclaration) {
                MethodDeclaration method = (MethodDeclaration) member;
                if (strMainMethod.equals(method.getName())) {
                    BlockStmt body = method.getBody();
                    MyVisitor myVisitor = new MyVisitor();
                    body.accept(myVisitor, null);
                    paramatersList = myVisitor.getParamatersList();
                }
            }
        }
    }

    return paramatersList;
}

private static class MyVisitor extends GenericVisitorAdapter {

    private ArrayList paramatersList= new ArrayList();

    public Object visit(MethodCallExpr n, Object arg) {

        if (strMethodName.equals(n.getName())){
                List<Expression> expressionList = n.getArgs();
                paramatersList.add(expressionList) ;
        }

        return super.visit(n, arg);
    }

    public ArrayList getParamatersList() {
        return paramatersList;
    }

}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.