如何获取 java 的泛型中的对象类型
1个回答
展开全部
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 {
/**
* 获取泛型的对象类型
*
* @param obj
* 泛型对象
*/
public static <T> 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);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询