通过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/