Java Generics type conversion puzzle

只谈情不闲聊 提交于 2019-12-22 05:42:14

问题


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);

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);

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.

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


回答1:


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>>

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



来源:https://stackoverflow.com/questions/10555773/java-generics-type-conversion-puzzle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!