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