簡體   English   中英

Java-有什么方法可以從引用類型推斷對象類型

[英]Java - Is there any way to infer the object type from a reference type

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運算符。 假設我沒有要比較的類型列表。

這很有可能-您只需調用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM