2014-09-23 41 views
1
public static void printType(Object o){ 
    type = **someWayToDeduceTheObjectType()** 
    fields = type.getDeclaredFields() 
    System.out.println("The type of the object is : " + type); 
    System.out.println("The fields of this type of class is : " + fields); 
} 

是否有可能从泛型引用类型推断传递对象的对象类型?爪哇 - 有什么办法从参考类型推断对象类型

如果不是,是什么原因?

我认为这是不可能的,因为存在铸造,但我不能明确确切的原因。

编辑:我不是指这里的instanceof操作符。假设我没有要比较的类型列表。

+0

http://stackoverflow.com/q/7313559/150818 – SJha 2014-09-23 12:49:50

+7

调用'o.getClass()'? – 2014-09-23 12:51:34

回答

2

它很可能 - 你只需要调用getClass()

public static void printType(Object o){ 
    type = o.getClass(); 
    fields = type.getDeclaredFields() 
    System.out.println("The type of the object is : " + type); 
    System.out.println("The fields of this type of class is : " + fields); 
}