简体   繁体   中英

How do I rewrite the following method without unchecked warnings?

private <K> Map<K, Object> createMap(final Class<K> keyClass) {
    final boolean isEnum = keyClass.isEnum();

    if(isEnum) {
                    // The following two lines throw warnings
        final Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>)keyClass;
        final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);

        return map;
    }
    else{
        final Map<K, Object> map = new HashMap<K, Object>();
        return map;
    }
}

Warnings

found   : java.lang.Class<K>
required: java.lang.Class<? extends java.lang.Enum<?>>
        final Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>)keyClass;
                                                                           ^
T.java:9: warning: [unchecked] unchecked call to EnumMap(java.lang.Class<K>) as a member of the raw type java.util.EnumMap
        final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
                                                   ^
T.java:9: warning: [unchecked] unchecked cast                                   
found   : java.util.EnumMap                                                     
required: java.util.Map<K,java.lang.Object>                                     
        final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
                                                   ^
3 warnings

There are some checks the compiler cannot do and it will give you a warning. The only way to avoid these in this method is to add annotation before the method

@SuppressWarnings("unchecked")

Even the collections like ArrayList so not compile without warnings.

You should use "instanceof" to check type, the compiler is aware of that check and won't throw a warning on the first line if you do that.

The second line should be written like "new EnumMap<K, Object>(enumCls);".

Well, there is at least a way to get the Class<? extends Enum<?>> Class<? extends Enum<?>> without warning:

if (keyClass.isEnum()) {
  Enum<?> e = (Enum<?>)keyClass.getEnumConstants()[0];
  Class<? extends Enum<?>> enumCls = e.getDeclaringClass();
  // snip
}

Still, as has already been said, there is no way to use K as type parameter for EnumMap. Hence suppressing the warning (after evaluating the risks) is perfectly fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM