Unchecked cast unchecked?

Alex Buckley alex.buckley at oracle.com
Tue Oct 29 22:52:16 UTC 2024


VarHandle::getAndSet(Object[]) is a signature polymorphic method, which 
means that the type of a method call is sensitive to an ensuing cast:

"... if the method invocation expression is the operand of a cast 
expression (§15.16), the compile-time result is the erasure of the type 
of the cast expression (§4.6)."  (JLS 15.12.3)

This has implications for how the method call is compiled, but it's moot 
for your program because the type of the method call is Object no matter 
how you slice it.

Casting from Object to type variable V is achieved by a narrowing 
reference conversion that is unchecked. So, I'd expect an "unchecked 
cast" warning, like for a non-signature polymorphic method.

Alex

On 10/29/2024 2:30 PM, Archie Cobbs wrote:
> Question: Should this program generate an unchecked cast warning?
> 
> import java.lang.invoke.VarHandle;
> class VarHandleCast<V> {
>      VarHandle vh;
>      V method(Object obj) {
>          return (V)vh.getAndSet(this, obj);  // unchecked cast?
>      }
> }
> 
> Currently, it does not.
> 
> Presumably that has something to do with this code in Types.java but I'm 
> not sure why this would mean there should be no warning:
> 
>      /**
>       * A polymorphic signature method (JLS 15.12.3) is a method that
>       *   (i) is declared in the java.lang.invoke.MethodHandle/VarHandle 
> classes;
>       *  (ii) takes a single variable arity parameter;
>       * (iii) whose declared type is Object[];
>       *  (iv) has any return type, Object signifying a polymorphic 
> return type; and
>       *   (v) is native.
>      */
>     public boolean isSignaturePolymorphic(MethodSymbol msym) {
>         List<Type> argtypes = msym.type.getParameterTypes();
>         return (msym.flags_field & NATIVE) != 0 &&
>                (msym.owner == syms.methodHandleType.tsym || msym.owner 
> == syms.varHandleType.tsym) &&
>                 argtypes.length() == 1 &&
>                 argtypes.head.hasTag(TypeTag.ARRAY) &&
>                 ((ArrayType)argtypes.head).elemtype.tsym == 
> syms.objectType.tsym;
>     }
> 
> Thanks,
> -Archie
> 
> -- 
> Archie L. Cobbs



More information about the compiler-dev mailing list