Skip to content

ClassCastException at runtime in with closure #1412

@mauromol

Description

@mauromol

I have an inconsistent behaviour with code like this.

package testcce;
public class TestCce {
	public static void main(String[] args) {
		final Foo f = new Foo();
		f.foobar();
		f.getBar().setBar("aaa");
	}
}
package testcce
import groovy.beans.Bindable
import groovy.transform.CompileStatic
@CompileStatic
class Bar {
	@Bindable
	String bar
	String other
}
package testcce
import groovy.beans.Bindable
import groovy.transform.CompileStatic
@CompileStatic
class Foo {
	Bar bar
	@Bindable
	String foo
	
	void foobar() {
		bar = new Bar()
		bar.with {
			addPropertyChangeListener('bar') {
				other = 'something'
				println 'ok'
			}
		}
		println 'end'
	}
}

If I run this from Eclipse (using Greclipse 4.8.0.v202210232216-e2206) I get the following ClassCastException:

Exception in thread "main" java.lang.ClassCastException: class testcce.Foo cannot be cast to class testcce.Bar (testcce.Foo and testcce.Bar are in unnamed module of loader 'app')
	at testcce.Foo$_foobar_closure1$_closure2.doCall(Foo.groovy:14)

If I compile and run this with Gradle/groovyc (with Groovy 2.5.19), all works fine.
What is really strange is that this is just a test case I could extract from my real project. With my real project I see the exact same exception even if I compile it with Gradle and run the application under Tomcat in the test and production environments.

A workaround is to add @CompileDynamic to Foo.foobar().

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions