I've encounter the instanceof issue in Groovy, and find the Class cannot be defined by variable, but isCase or isAssignableFrom works as expected.
Here are details :
// works
assert '' instanceof java.lang.String
// not working
Class clz = ''.getClass()
assert '' instanceof clz // ERROR: unable to resolve class clz
assert '' in clz // works
// debug info:
println clz // class java.lang.String
println clz.getClass() // class java.lang.Class
isCase() and isAssignableFrom() works, I assume because of those two are function
Class clz = ''.getClass()
// works
assert clz.isCase( '' )
assert clz.isCase( [] ) == false
// works
assert clz.isAssignableFrom( ''.getClass() )
assert clz.isAssignableFrom( [:].getClass() ) == false
But why instanceof cannot be using class-type variable ? by the way, groovy version is Groovy Version: 4.0.18 JVM: 21.0.2 Vendor: Homebrew OS: Mac OS X
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.2
probably the best explanation is here ^^^
instanceofoperator works at compile-time and at run-time. to make checks at compile time it requires exact class name.more, since jdk 16 there is a new syntax (https://openjdk.org/jeps/394)
instead of
you can use
with this syntax it's obvious that you need exact type and not a class reference