我会尽力解释我的问题,希望有人能帮助我。
结对类:
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
}
配对类:
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对象中。如何从泛型类型转换为字符串或 boolean 类型?反过来你又如何做呢?
我找到了将泛型类型转换为字符串的答案:
Class<?> value = getValue();
if (value.isInstance(String.class))
String newValue = (String)(Object) value; // is it correct?
那么如何将 String 转换为 Class< ?> 并将数据存储到 arraylist 中?因为我想创建:
Pair pair = new Pair("name", value); // but value can be String, Integer, or Boolean
谢谢。
最佳答案
我首先将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);
关于java - 如何在 Java 数组列表中存储泛型类型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984468/