我们可以为通用类型提供类型吗?

时间:2020-12-24 20:14:38

Say we have the function:

假设我们有这个功能:

<T> T   getFromCache (ClassType<T>   clazz);

For strings:

String str =   getFromCache(String.class);

For maps what I am currently thinking of doing:

对于我目前正在考虑做的地图:

//… 
Map<String, SomeData>   anotherMapObject  = getFromCache( HashMap.class);

Can we be more specific than this ?

我们可以比这更具体吗?

One solution ofcourse is to wrap ‘HashMap’ in one class. But if we don’t want to do that then is there a better solution ?

一个解决方案是将“HashMap”包装在一个类中。但如果我们不想这样做,那么有更好的解决方案吗?

1 个解决方案

#1


0  

If you want the map implementation to be passed in you can do this:

如果您希望传递地图实现,则可以执行以下操作:

private <M extends Map> Map<String, String> get(Class<M> m) throws Exception {
        return (Map<String, String>) m.newInstance();
    }

You can parametrize the key and value types like this:

您可以像这样参数化键和值类型:

private <M extends Map<K, V>, K, V> M getMap(Class<M> m, Class<K> k, Class<V> v)

#1


0  

If you want the map implementation to be passed in you can do this:

如果您希望传递地图实现,则可以执行以下操作:

private <M extends Map> Map<String, String> get(Class<M> m) throws Exception {
        return (Map<String, String>) m.newInstance();
    }

You can parametrize the key and value types like this:

您可以像这样参数化键和值类型:

private <M extends Map<K, V>, K, V> M getMap(Class<M> m, Class<K> k, Class<V> v)