java - 使用显式类型参数调用静态导入的方法

标签 java generics

这是我的问题的后续:Weird Java generic .

如果我有这样的代码:

Casts.<X, T> cast(iterable[index]);

我可以添加静态导入并执行吗:

<X, T> cast(iterable[index]);

Eclipse 不允许这样做。但是在 Eclipse 中看到这么多静态导入的错误后,我不太确定。

最佳答案

不,你不能:我刚刚通过一些测试代码确认了这一点。

PS > javac -version
javac 1.6.0_04

Casts.java

public class Casts
{
    public static <From, To> 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.<Integer, Number>cast(integer);

        // This one fails compilation:
        // PS> javac Test.java
        // Test.java:11: illegal start of expression
        //             final Number number = <Integer, Number>cast(integer);
        //                                                    ^
        // Test.java:11: not a statement
        //             final Number number = <Integer, Number>cast(integer);
        //                                                        ^
        final String string = <Integer, String>cast(integer);
    }
}

关于java - 使用显式类型参数调用静态导入的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2050317/

相关文章:

java - List<A> 不能发送到方法( List<superclass-of-A> )——为什么不呢?

java - Play 自定义对象值的框架表单绑定(bind)映射

java - 搜索具有自定义 id 的对象

java - 类新实例上的 Spring @Autowired

java - android - 如何检测正在激活的应用程序

c# - 是否有将通用集合公开为只读的良好模式?

c# - 获取对通用对象<T> 的引用

C#:如何使用 LINQ 从 IDictionary<E, ICollection<T>> 的集合中删除项目?

java - 您的安全设置已阻止使用过期或尚未生效的证书签名的应用程序运行

C# 基类型列表添加通用子实例