不同上下文中同一类的变量

发布于 2024-10-08 16:56:57 字数 744 浏览 0 评论 0原文

我正在尝试将 groovy 嵌入到 java 应用程序中,但遇到了一个奇怪的问题。假设我在 groovy 脚本中定义了这个类:

class MyClass {
    String a;
}

然后我实例化它并将其放入我的应用程序上下文范围(Map 存储在我的主应用程序中,并且在脚本之间提供公共存储)。

MyClass c = new MyClass()
c.a = "Hello world!"
appContext.share.put("myclass.instance",c)

然后,在其他脚本中(单独运行,具有自己的上下文,但来自相同的源,包括 MyClass.groovy 文件),我尝试读回变量:

MyClass c = (MyClass) appContext.share.get("myclass.instance")

并得到一个关于无法将 MyClass 实例强制转换为的壮观异常我的班级:)。

基本上我明白可能是什么问题,每次编译脚本时,它都会创建具有不同 ID 但名称相同的类的新实例,并且它们彼此不兼容。问题是,在不序列化/反序列化所有共享对象且不使用反射的情况下,我该如何做我想做的事情?

必须注意的是,我无法将 MyClass 类移至 Java 代码,它必须保留在脚本中,因为它是脚本逻辑的一部分。

提前致谢。

I'm trying to embed groovy in java application and got a weird problem. Let's say I have this class defined in groovy script:

class MyClass {
    String a;
}

Then I instantiate it and put it into my application context scope (Map<String, Object> stored in my main application and providing a common storage between scripts).

MyClass c = new MyClass()
c.a = "Hello world!"
appContext.share.put("myclass.instance",c)

Then, in other script (that is run separately, with it's own context, but from the same sources including MyClass.groovy file), I try to read the variable back:

MyClass c = (MyClass) appContext.share.get("myclass.instance")

And get a spectacular exception about not being able to cast MyClass instance to MyClass :) .

Basically I understand what could be the problem, each time I compile the script it creates new instances of classes with different ID's but same names, and they are incompatible with each other. Question is, how can I do what I am trying to do without serializing/deserializing all shared objects and without using reflection?

It has to be noted that I can't move the MyClass class to Java code, it has to remain in the script as it is part of script logic.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北渚 2024-10-15 16:56:57

如果您尝试将 appContext.share.get("myclass.instance") 强制转换为 MyClass 会怎样? as 执行更“严厉”的转换,它甚至可以将 Map 转换为类。它就像c.properties = appContext.share.get("myclass.instance").properties

What if you try casting with appContext.share.get("myclass.instance") as MyClass ? as performs a more "harsh" cast, it can even cast Map to a class. It is like c.properties = appContext.share.get("myclass.instance").properties.

淡淡绿茶香 2024-10-15 16:56:57

首先要建议的是 - 您可以使用 Groovy 的动态特性,并在第二种情况下避免类型声明:

def c = appContext.share.get("myclass.instance")

但是,据我了解,在幕后它将使用反射。

First thing to suggest - you may use Groovy's dynamic nature and avoid type declaration in second case:

def c = appContext.share.get("myclass.instance")

However, under the hood it will use reflection, as I understand.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文