How to Obtain Return Values in Static Analysis of Java

Asked 5 months ago, Updated 5 months ago, 10 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.


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() {
        return ret*2;

Retrieved Results


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" +
        ASTParser parser = ASTParser.newParser (JLS8);
        CompilationUnit=(CompilationUnit) parser.createAST(new NullProgressMonitor());

        MyVisitor visitor = new MyVisitor();

class MyVisitor extensions ASTVisitor {
    @ Override
    public boolean visit (ReturnStatement node) {
        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

© 2023 OneMinuteCode. All rights reserved.