简体   繁体   English

Java Generics:从泛型中检索类型 object

[英]Java Generics : Retrieving the type from a generic object

I have a generic class Class1<K, V> which takes two types.我有一个通用的 class Class1<K, V> 有两种类型。 Now I want to maintain a map which maps String to Class1 objects ie Map<String, Class1>.现在我想维护一个 map,它将 String 映射到 Class1 对象,即 Map<String, Class1>。 Can I retrieve the types (K,V) of each Class1 Object while I iterate through Map?我可以在迭代 Map 时检索每个 Class1 Object 的类型(K,V)吗?

ie lets think of code as below即让我们想想代码如下

Map<String, Class1> map;
map.put("1", Class1<String, Integer> obj1);
map.put("2", Class1<String, Double> obj2);
map.put("3", Class1<Integer, Double> obj3);

Now when I iterate over the map... Can I somehow get the types(K, V) of each Class1 object??现在,当我遍历 map 时......我能以某种方式获得每个 Class1 object 的类型(K,V)吗?

It's not possible according to JVM specification.根据 JVM 规范,这是不可能的。

Generic types are available only at compile time.泛型类型仅在编译时可用。 At runtime ther're only Object .在运行时只有Object

All you have is 2 options:你只有两个选择:

  1. Add class definition variable to your objects and us it when you need this info.将 class 定义变量添加到您的对象中,并在您需要此信息时使用它。
  2. Eg for List<Object> as well as for other collections if it's not empty, you can get an item from it and get item.getClass() .例如,对于List<Object>以及其他 collections 如果它不为空,您可以从中获取一个项目并获取item.getClass()

PS Buy the way, your approach is not correct to solve this issue. PS购买方式,你的方法不正确,不能解决这个问题。 You could implement an interface like:您可以实现如下接口:

interface TypeConverter {
    boolean isValid(String str);   // call it before to check if current converter valid for required transform or not

    Class1 converts(String str);  // call it to convert 
}

And for each required types you have to create separate converter (this is Strategy Pattern).对于每个必需的类型,您必须创建单独的转换器(这是策略模式)。 And your final code could look like this:您的最终代码可能如下所示:

final TypeConverter converters = new ArrayList<>();
converters.add(new OneTypeConverter());
converters.add(new TwoTypeConverter());

public static Class1 convert(String str) {
    for(TypeConverter convereter : converters)
        if(converter.isValid(str))
            return converter.convert(str);
  
    throw new RuntimeException("No suitable converter found");
}

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

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