判斷Object中數據類型(已知類型、未知類型))

一、已知數據類型

接收到的數據類型爲Object,如果知道數據的類型可以使用ObjectMapper進行處理,得到裏面的參數。

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
public class Test02 {
    public static void main(String[] args) throws IOException {
        String str = "{\"one\":\"yes\",\"key\":\"value\"}";
        ObjectMapper mapper = new ObjectMapper();
        HashMap hashMap = mapper.readValue(str, HashMap.class);
        System.out.println(hashMap.toString());
    }
}

二、未知數據類型

假如,不清楚數據類型,或者接收到的數據類型有很多種,這樣就需要對接收到的數據,按類型進行分類處理,這就要求對接收到的數據類型進行判斷。

方法一、equals進行判斷

HashMap<String, String> hashMap = new HashMap<>();
Object object = (Object)hashMap;
if (HashMap.class.equals(object.getClass())){
    System.out.println("true");
}

方法二、instanceof進行判斷

測試一個對象obj是否爲一個類的實例;obj必須爲引用類型,不能是基本類型;obj爲null,則返回false。

HashMap<String, String> hashMap = new HashMap<>();
Object obj = (Object)hashMap;
if (obj instanceof HashMap){
    System.out.println("True");
}

方法三、通過class獲取類型

HashMap<String, String> hashMap = new HashMap<>();
Object object = (Object)hashMap;
String simpleName = object.getClass().getSimpleName();
if ("HashMap".equals(simpleName)){
    System.out.println("True");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章