如何获取 java 的泛型中的对象类型
答案:2 悬赏:0 手机版
解决时间 2021-04-23 21:48
- 提问者网友:流星是天使的眼泪
- 2021-04-23 01:19
如何获取 java 的泛型中的对象类型
最佳答案
- 五星知识达人网友:第幾種人
- 2021-04-23 02:56
class Human {
public String toString() {
return "This is human";
}
}
class Man extends Human {
public String toString() {
return "This is man";
}
}
class Woman extends Human {
public String toString() {
return "This is woman";
}
}
public class GetObj {
public static void showInstance(T obj) {
try {
Object tmpObj = obj.getClass().newInstance();// 实例化泛型对象
if (tmpObj instanceof Human) {// Human的对象
System.out.println(tmpObj);
} else if (tmpObj instanceof Man) {// Man的对象
System.out.println(tmpObj);
} else {// Woman的对象
System.out.println(tmpObj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Human h = new Human();
showInstance(h);
Man m = new Man();
showInstance(m);
Woman w = new Woman();
showInstance(w);
}
}
public String toString() {
return "This is human";
}
}
class Man extends Human {
public String toString() {
return "This is man";
}
}
class Woman extends Human {
public String toString() {
return "This is woman";
}
}
public class GetObj {
public static
try {
Object tmpObj = obj.getClass().newInstance();// 实例化泛型对象
if (tmpObj instanceof Human) {// Human的对象
System.out.println(tmpObj);
} else if (tmpObj instanceof Man) {// Man的对象
System.out.println(tmpObj);
} else {// Woman的对象
System.out.println(tmpObj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Human h = new Human();
showInstance(h);
Man m = new Man();
showInstance(m);
Woman w = new Woman();
showInstance(w);
}
}
全部回答
- 1楼网友:舍身薄凉客
- 2021-04-23 03:15
private static class getfieldclass(field field) {
class fieldclazz = field.gettype();
if (fieldclazz.isassignablefrom(list.class)) {
type fc = field.getgenerictype(); // 关键的地方,如果是list类型,得到其generic的类型
if (fc instanceof parameterizedtype) // 如果是泛型参数的类型
{
parameterizedtype pt = (parameterizedtype) fc;
fieldclazz = (class) pt.getactualtypearguments()[0]; //得到泛型里的class类型对象。
}
}
return fieldclazz;
}正好这几天刚写了相关代码,供参考
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯