How to Obtain Return Values in Static Analysis of Java

Asked 1 months ago, Updated 1 months ago, 0 views

Thank you for your help.

Currently, we are conducting static analysis of java in java and would like to get the return value of the method.
I was able to get the method name using imethod, but I don't know how to get the return value.

For example, if the method says the following, I would like to get the variable name hoge instead of the return value (0 in this case).

public int hoge(){
  inthoge = 0;
  return hoge
}

That's all.
Thank you for your cooperation.

java

2022-09-30 11:50

1 Answers

Since you are using IMethod, you assume that you are trying to retrieve the expression specified in the return statement from the class file, but I don't think you can get the necessary information.
The class file does not appear to contain the source code information for the return statement.
I tried using the javap command or hexadecimal dump, but I couldn't find any information.

You can use node.getExpression() to get the information you need within the visit method, where ReturnStatement node is the provisional argument by creating a class that inherits ASTVisitor.

Statically parsed code

public class Myclass{
    public into hoge() {
        intret;
        return ret*2;
    }
}

Retrieved Results
ret*2

code

import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ReturnStatement;

import static org.eclipse.jdt.core.dom.AST.JLS8;

public class Main {
    public static void main(String[]args) {
        String source = "public class Myclass {" +
                "   public int hoge() {\r\n" +
                "       intret=0;\r\n"+
                "       return ret*2;\r\n"+
                "   }\r\n"+
                US>"}\r\n" +
                "";
        System.out.println(source);
        ASTParser parser = ASTParser.newParser (JLS8);
        parser.setSource(source.toCharArray());
        CompilationUnit=(CompilationUnit) parser.createAST(new NullProgressMonitor());

        MyVisitor visitor = new MyVisitor();
        unit.accept(visitor);
        System.out.print("END");
    }
}

class MyVisitor extensions ASTVisitor {
    @ Override
    public boolean visit (ReturnStatement node) {
        System.out.println("node=["+node.toString()+"]");
        System.out.println("node.getExpression()=["+node.getExpression().toString()+"]");
        return super.visit(node);
    }
}

Run Results

node=[return ret*2;
]
node.getExpression() = [ret*2]


2022-09-30 11:50

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.