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) ap开发者_运维百科pContext.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.
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
.
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.
精彩评论