Java – create with class Key immutablemap problem

I'm trying to create an immutable map that maps classes to strings (Note: This is of course just an example!) But, like

ImmutableMap<Class<?>,String> map = ImmutableMap.of( 
    Integer.class,"Integer",Date.class,"Date" 
);

Give me the following error

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

Strangely, if I add a transformation to class Any (!) Key, i.e

ImmutableMap<Class<?>,String> map = ImmutableMap.of(
    Integer.class,"Date",(Class<?>) String.class,"String",long.class,"Long"
);

Will work well I am puzzled by this behavior: why is there no actor for a? All these are classes. It really won't be better than class More general, so why doesn't it work? Second, why can actors on any key work?

(sidenote: if you want to know why I even want to do something like this – yes, it's because of reflection...)

Editor: I actually just thought it would work, but I want to understand the above behavior

ImmutableMap<Class<?>,String> map = ImmutableMap.<Class<?>,String>builder()
    .put( Integer.class,"Integer" )
    .put( Date.class,"Date" )
    .build();

Solution

This is how the compiler infers type parameters when you pass inconsistent method parameters

Class < date and gt; And class < integer > are captured and can be converted to all of the following:

> Class<? Extended Object > > class > class >

Therefore, class k is inferred as all mixtures:

K := Class<? extends Object&Serializable&Comparable<?>>

That is, the return value of the method is really:

ImmutableMap<Class<? extends Object&Serializable&Comparable<?>>,String>

Of course, you cannot assign it directly to immutablemap < class String > because they are incompatible types Also note that you cannot explicitly declare your map as above, because you cannot give multiple boundaries of wildcards This is only the type inferred by the compiler

ImmutableMap<Class<?>,String>of( 
    Integer.class,"Date" 
);

This will now work because the compiler knows from the explicit type parameter that the return value will be – immutablemap < class , String>

Once you convert any element to class , Because class Represents all instances of all classes < T > in the family, so it is the public supertype of all class instances Therefore, the type parameter will be inferred as class Automatic It will work properly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>