Björn Kautler created GROOVY-12469:
--------------------------------------
Summary: SC: static compilation inserts wrong cast, derived from
generic return type when assigned to a variable
Key: GROOVY-12469
URL: https://issues.apache.org/jira/browse/GROOVY-12469
Project: Groovy
Issue Type: Bug
Affects Versions: 6.0.0, 5.1.3, 4.0.33, 5.0.3, 3.0.25, 2.5.23
Reporter: Björn Kautler
Given the following snippet:
{code:groovy}
import java.lang.annotation.Annotation
import java.lang.annotation.Retention
import java.lang.annotation.Target
import groovy.transform.CompileStatic
@CompileStatic
<T extends Annotation> T getRetention(Class<T> clazz) {
Target.getAnnotation(Target)
}
@CompileStatic
def foo() {
Annotation x = getRetention(Retention) /*as Annotation*/
}
foo().toString()
{code}
This compiles fine under all versions, but fails with a {{GroovyCastException}}
in all versions.
The generated byte-code under SC has a cast on {{Retention}} in this, even
though the variable is of type {{Annotation}} explicitly.
Commenting in the {{as Annotation}} cast makes it work.
Removing the {{Annotation x =}} also makes it work.
Removing the {{@CompileStatic}} or replacing it by {{@TypeChecked}} of course
also makes it work.
I'd say static-compilation should here not insert an unnecessary cast to
{{{}Retention{}}}, but at most a cast to {{Annotation}} as that is, what the
variable needs and which should be consistent with JVM type-erasure, and also
with the variant without the variable. Even with the method returning
{{Annotation}} instead of {{def}} it works just fine. Just if the method
declares to return {{Retention}} explicitly, the cast exception comes, but then
rightfully.
--
This message was sent by Atlassian Jira
(v8.20.10#820010)