Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy map coercion produced <class>_groovyProxy

Tags:

java

groovy

I have a java class which I'm trying to instantiate.

PackageGenerator gen = [
      fileName: "file.xml",
      platform: "windows",
      version: "1.0"]
println ReflectionToStringBuilder.toString(gen);

produce:

PackageGenerator_groovyProxy[fileName=<null>, platform=<null>, version=<null>]

but if I write it with the .with way:

PackageGenerator gen = new PackageGenerator()
gen.with {
    fileName = "file.xml"
    platform = "windows"
    version = "1.0"
}
println ReflectionToStringBuilder.toString(gen);

produces:

PackageGenerator[fileName="file.xml", platform="windows", version="1.0"]

what's causing the groovy proxy class to be used instead of the actual class?

like image 241
stewart99 Avatar asked May 29 '26 01:05

stewart99


1 Answers

The _groovyProxy suffix is added when Proxy implementation is created if the original object is not assignable to the demanded type. I believe what is happening here is that

PackageGenerator gen = [
  fileName: "file.xml",
  platform: "windows",
  version: "1.0"]

is the same as

PackageGenerator gen = [
  fileName: "file.xml",
  platform: "windows",
  version: "1.0"] as PackageGenerator

and as a Map cannot be cast to PackageGenerator a proxy is generated.

You can easily overcome this by using a map constructor

PackageGenerator gen = new PackageGenerator(
  fileName: "file.xml",
  platform: "windows",
  version: "1.0")

which implementation is very close to what you have written in the second example

like image 59
musketyr Avatar answered May 31 '26 15:05

musketyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!