【问题标题】:How to get the value passed to a variable?如何获取传递给变量的值?
【发布时间】:2021-05-27 18:26:19
【问题描述】:

我正在尝试评估一个将变量初始化为一个值的代码 sn-p。有没有办法使用java获取字段值?对于以下代码:

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

假设这是用户编写的代码,我想从后端检查长度和宽度的值。如何找回?

【问题讨论】:

  • 这些是方法中的局部变量,在该方法的运行时之外,它们不存在。
  • 我不明白这个问题。请说清楚。你使用什么样的后端,变量是如何传递的?
  • 我正在尝试使用 javaParser 从文件中读取代码。我想获取方法中声明的变量。

标签: java jshell javaparser


【解决方案1】:

你可以去查看javaParser 这有助于自动化您在 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 
}

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2022-01-19
    • 2022-11-05
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多