Invoking statically imported method with explicit type parameters

后端 未结 5 1900
梦毁少年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条回答
  •  -上瘾入骨i
    2021-01-03 20:26

    No, you can't : I just confirmed this via some test code.

    PS > javac -version
    javac 1.6.0_04
    

    Casts.java

    public class Casts
    {
        public static  To cast(final From object)
        {
            return (To)object;
        }
    }
    

    Test.java

    import static Casts.cast;
    
    public class Test
    {
        public static void main(String[] args)
        {
            final Integer integer = new Integer(5);
    
            // This one compiles fine.
            final Number number = Casts.cast(integer);
    
            // This one fails compilation:
            // PS> javac Test.java
            // Test.java:11: illegal start of expression
            //             final Number number = cast(integer);
            //                                                    ^
            // Test.java:11: not a statement
            //             final Number number = cast(integer);
            //                                                        ^
            final String string = cast(integer);
        }
    }
    

提交回复
热议问题