作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我会尽力解释我的问题,希望有人能帮助我。
对类:
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对象中。如何从泛型类型转换为 String 或 Boolean?你如何反过来做?
我找到了将泛型类型转换为字符串的答案:
Class<?> value = getValue();
if (value.isInstance(String.class))
String newValue = (String)(Object) value; // is it correct?
那么我如何将一个字符串转换为类< ?> 并将数据存储到数组列表中呢?因为我想创建:
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 arraylist 中存储具有泛型类型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984468/
我是一名优秀的程序员,十分优秀!