Invoking statically imported method with explicit type parameters

后端 未结 5 2023
梦毁少年i
梦毁少年i 2021-01-03 20:03

This is the follow up of my question here: Weird Java generic.

If I have a code like this:

Casts. cast(iterable[index]);
<
5条回答
  •  情书的邮戳
    2021-01-03 20:24

    As far as I've read, a shortcoming of the static import mechanism is that you must specify the calling object/class if you wish to provide formal parameters. In this example, it's not very clear why there are two generic parameters, but if you wish to avoid having to specify the calling object/class you can type hint through a cast of the arguments as such:

    public static  E foo(E e) {}
    
    Number n = foo((Number)3);
    

    With the type hint, the type inference will return an object of type Number, instead of Integer as it would have reasoned otherwise.

提交回复
热议问题