-2

I am trying to evaluate a code snippet that has variables initialised to a value. Is there a way to get the field values using java? For the below code:

public void testArea(){
    int length = 5;
    int breadth = 6;
    ...
}

Suppose this is the code written by a user, I want to check the value of length and breadth from the backend. How to retrieve this?

Rakshita
  • 1
  • 2
  • 2
    those are local variables in a method, outside of the runtime of that method, they don't exist. – Stultuske Feb 25 '21 at 11:45
  • I don't understand the question. Please clarify. What kind of backend are you using, how do the the variables get passed? – Benjamin M Feb 25 '21 at 11:45
  • I am trying to read the code from a file using javaParser. I want to get the variables declared in the method. – Rakshita Feb 26 '21 at 04:43

1 Answers1

0

You can go check javaParser which help automate your coding in java

    JavaParser javaParser = new JavaParser();
    ParseResult<CompilationUnit> compilationUnitParseResult = javaParser
                    .parse(ParseStart.COMPILATION_UNIT, Providers.provider("PATH_TO_FILE"));
    Optional<CompilationUnit> optionalCompilationUnit = compilationUnitParseResult.getResult();
     compilationUnit = optionalCompilationUnit.get();
    List<VariableDeclarator> list = compilationUnit.finAll(VariableDeclarator.class);
if (list.size()>0){
    VariableDeclarator varibaleDeclrator =  list.get(0);
    varibaleDeclrator.getInitializer().get()// this will give you the value of the varible intialized with 
}