Java泛型类型转换难题 [英] Java Generics type conversion puzzle

查看:445
本文介绍了Java泛型类型转换难题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Google的Guava ImmutableSet类创建一组带有时间属性(java.util.Date和org.joda.time.DateTime)的不可变类。

I'm attempting to use Google's Guava ImmutableSet class to create a set of immutable classes with timelike properties (java.util.Date, and org.joda.time.DateTime).

private static final ImmutableSet<Class<?>> timeLikeObjects = ImmutableSet.of(Date.class, DateTime.class);

我完全难以理解为什么我得到这个编译器错误(eclipse中的Java 1.6) 。

I'm completely stumped as to why I'm getting this compiler error (Java 1.6 in eclipse).

Type mismatch: cannot convert from ImmutableSet<Class<? extends Object&Serializable&Comparable<? extends Comparable<?>>>> to ImmutableSet<Class<?>>

请注意,这是有效的:

Note that this works:

private static final ImmutableSet<?> timeLikeObjects = ImmutableSet.of(Date.class, DateTime.class);

然而,我明显地忽略了timeLikeObjects类型的一部分通用描述。

However I obviously loose part of the generic description of the timeLikeObjects type.

我从来没有在泛型描述中遇到&符号,它看起来不是有效的语法。

I've never run across the ampersand symbol in a generic description, and it doesn't appear to be valid syntax.

一种在Java泛型中指定多重继承的方法,我只是缺少一个方法?

Is there a way to specify multiple inheritance in Java Generics that I'm just missing?

推荐答案

基本上,编译器试图对您。它正在为你设计一些限制,并尝试将它们用于 的返回类型。

Basically the compiler is trying to be smart for you. It's working out some bounds for you, and trying to use them for the return type of of.

幸运的是,你可以通过明确的方式来解决它:

Fortunately, you can fix it by being explicit:

private static final ImmutableSet<Class<?>> timeLikeObjects =
    ImmutableSet.<Class<?>>of(Date.class, DateTime.class);

& 部分有效的语法 - 这是你如何指定多种类型的边界,例如:

The & part is valid syntax - it's how you specify bounds for multiple types, e.g.

public class Foo<T extends Serializable & Comparable<T>>

这意味着您只能指定 T 实现 Serializable Comparable< T>

That means you can only specify types for T which implement Serializable and Comparable<T>.

这篇关于Java泛型类型转换难题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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