如何在Java arraylist中存储泛型类型的数据

时间:2016-08-16 21:04:39

标签: java

我会尽力解释我的问题,希望有人可以帮助我。

配对课程:

public class Pair {
   String key;
   Class<?> value;
   public Pair(String key, Class<?> value){
      this.key = key;
      this.value = value;
   };
   // you have the setter and getter methods
}

Pairs class:

public class Pairs {
   Pair[] paris = new Pair[0];
   // you have the setter and getter methods
   public void addPair(Pair pair) {
      // assume it will add a pair to the array
   }
}

问题:我需要从数据库表中加载数据。这里的列类型不同。有BOOLEAN,VARCHAR,DATE等。所以我需要读取并将具有相应java类型的数据存储到Pair对象中。如何从泛型类型转换为String或Boolean?那你怎么做呢?

我找到了将泛型类型转换为String的答案:

Class<?> value = getValue();
if (value.isInstance(String.class))
String newValue = (String)(Object) value; // is it correct?

然后我如何将String转换为Class&lt; ?&GT;并将数据存储到arraylist?因为我想创建:

Pair pair = new Pair("name", value); // but value can be String, Integer, or Boolean

感谢。

1 个答案:

答案 0 :(得分:4)

我会以Pair通用的方式开始。像,

public class Pair<T> {
   String key;
   T value;
   public Pair(String key, T value){
      this.key = key;
      this.value = value;
   };
   // ...
}

然后为实际的列类型实例化Pair。像,

Pair<String> p = new Pair<>("a", "b");

Pair<Integer> p = new Pair<>("a", 1);