简体   繁体   English

如何在Java中使用泛型类型获取类

[英]How to get class with generics types in Java

I am trying to make a method call like this, 我正在尝试进行这样的方法调用,

public class GenericsTest<T> {

    public static <T> Map<String, T> createMap(Class<? extends Map<String, T>> clazz) {
        return null;
    }

    public static void main(String[] argv) {
        Map<String, Integer> result = createMap(TreeMap.class);
    }
}

But I am getting this error, 但是我得到这个错误,

<T>createMap(java.lang.Class<? extends java.util.Map<java.lang.String,T>>) in test.GenericsTest<T> cannot be applied to (java.lang.Class<java.util.TreeMap>)

How to fix this problem? 如何解决这个问题?

Map<String, Integer> instance = new TreeMap<String, Integer>();

@SuppressWarnings("unchecked")
Map<String, Integer> map =
    createMap((Class<? extends Map<String, Integer>>)instance.getClass());

map.put("x", 1);

System.out.println("THIS IS x: " + map.get("x"));

This will appropriately print out 1. The implementation of the method is most likely 这将适当地打印出1。最有可能实现该方法

try
{
    return clazz.newInstance();
}
catch (Exception e)
{
    throw new RuntimeException(e);
}

A better implementation of their API would be for them to ask you for the type, T , and for them to give back a Map of their choosing instead of asking you for all of the details. 更好地实现他们的API的方法是让他们向您询问类型T ,并让他们返回自己选择的Map ,而不是要求您提供所有详细信息。 Otherwise, as long as they are not filling in the Map with any data, you can instantiate a Map with the generic type argument yourself like so: 否则,只要它们不使用任何数据填充Map ,就可以自己使用泛型类型参数实例化Map ,如下所示:

public static <T> Map<String, T> getMap()
{
    return new TreeMap<String, T>();
}

You can then access that without a warning: 然后,您可以在没有警告的情况下访问它:

// note the lack of type arguments, which are inferred
Map<String, Integer> instance = getMap();

// alternatively, you could do it more explicitly:
// Map<String, Integer> instance = ClassName.<Integer>getMap();

There's really no reason for them to ask you for the Class type of your Map except to give you back an exact match to the implementation (eg, if you stick in a HashMap , then you will get back a HashMap , and if you stick in a TreeMap , then you will get back a TreeMap ). 他们真的没有理由要求您提供MapClass类型,只是给您与实现完全匹配的信息(例如,如果您坚持使用HashMap ,那么您将获得HashMap ,如果您坚持使用一个TreeMap ,然后您将获得一个TreeMap )。 However, I suspect that the TreeMap will lose any Comparator that it was constructed with, and since that is an immutable ( final ) field of TreeMap , then you cannot fix that; 但是,我怀疑TreeMap会丢失Comparator它一起构造的任何Comparator ,并且由于那是TreeMap一个不变的( final )字段,因此您无法修复该问题; that means that the Map is not the same in that case, nor is it likely to be what you want. 这意味着在这种情况下, Map是不一样的,也不可能是您想要的。

If they are filling in the Map with data, then it makes even less sense. 如果他们用数据填充Map ,那就没有意义了。 You could always pass in an instance of a Map to fill, or have them return a Map that you can simply wrap (eg, new TreeMap<String, Integer>(instance); ), and they should know which Map offers the most utility to the data. 您总是可以传入一个Map实例来填充,或者让他们返回一个您可以简单包装的Map (例如new TreeMap<String, Integer>(instance); ),他们应该知道哪个Map提供的实用性最高数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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