2014-09-23 47 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); 
}