java - 通过 Groovy 脚本访问 Java 局部变量

标签 java groovy

通过Groovy脚本(元编程),我可以访问和修改在java类中全局声明的变量。即使我可以使用脚本调用或重写 java 方法。但我找不到任何方法来访问类的特定方法内的变量。

考虑一个类 MethodInjection.java

public class MethodInjection {

static String text = "";

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

public static void Execute() throws IOException 
{
    System.out.println("Before Value : "+text);        
    String script = loadScript("Path_to_script");
    Script scripting = new GroovyShell().parse(script);
    scripting.run();
}

public static void print()
{
    System.out.println("After Value : "+text); 
}

public static void access()
{
    String local ="";
}

static String loadScript(String fileName) throws IOException 
{
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try 
    {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) 
        {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } 
    finally 
    {
        br.close();
    }
}}

同样的脚本是:

import methodinjection.MethodInjection

def access = new MethodInjection()
access.text = "Modified"
access.metaClass.access.local = "change"
access.print()
println access.metaClass.access.local

我得到的输出为

Before Value : 
After Value : Modified
groovy.lang.ExpandoMetaClass$ExpandoMetaProperty@75f9ecc

但是我需要修改局部变量并通过Groovy脚本打印它。

尝试了很多方法都没有找到

最佳答案

简短回答:Groovy 无法做到这一点。

更长的答案:最终 Groovy 取决于 JVM 和 Reflection 提供的功能。它实际上是故意不包含需要将字节码转换为“正常”Groovy 逻辑(如元编程)的功能。局部变量仅作为“槽”存在,在方法字节码中可能有名称。因此,您需要一个字节码操作库,正如这里已经提到的那样。

关于java - 通过 Groovy 脚本访问 Java 局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54513432/

相关文章:

java - 防止 NullPointerException 警告的最佳方法?

java - 在java中将图像拼接在一起

java - 尝试以编程方式重新使用具有细微差异的布局

grails - Grails 2.4.4-如何从Groovy类重定向(非 Controller )

ant - 启用来自 groovy 的 AntBuilder 的详细输出

grails - Groovy:访问父类中的属性

java - 通过系统属性更改单个类的记录器级别

java - GEB:驱动程序未设置为 Browser.driver

Groovy 属性迭代

java - 如何使用 to_char 函数按条件添加到 Criteria 订单