Java 8泛型类型转换在使用java 7传递时失败 [英] Java 8 generic type conversion fails where as it was passing with java 7

查看:238
本文介绍了Java 8泛型类型转换在使用java 7传递时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题,因此将其作为完整的解决方案发布 -

I faced this issue and hence posting it as complete solution -

使用Java 8,以下代码将失败并出现运行时异常。问题是getInteger方法返回一个通用的Integer类型,print方法需要精确的Object Type。

With Java 8, the below code will fail with Runtime exception. The problem is getInteger method is returning a generic Integer type and print method expects exact Object Type.

public static void main(String[] args) {
    print(getInteger());
}

private static <T> T getInteger() {
    return (T)new Integer(10);
}

private static void  print(Object...o1){
    for(Object o: o1){
       System.out.println(o);
    }
}


推荐答案

As解决方案的一部分选择以下任何一种。

As part of solution choose any of the following.

两次调用中断方法调用和参数传递 -

Break method call and argument pass in two calls –

Integer i = getInteger();

print(i);

print(i);

使用Typed参数调用print方法 -

Call print method with Typed argument –

  print(Main.<Integer>getInteger());

我希望它会有所帮助。

这篇关于Java 8泛型类型转换在使用java 7传递时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆