java#泛型
1. 方法的泛型
有时候写一个方法,需要接受各种类型的参数,这是可以使用Object作为类型,也可以使用方法参数泛型,参数写 T,并在返回值的前面写<T>表示用了泛型,比如:
public <T> Map<String, Object> toMap(T obj) throws IllegalAccessException { HashMap<String, Object> ret = new HashMap<>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); String key = field.getName(); if (key.equals("serialVersionUID")) { continue; } Object value = field.get(obj); ret.put(key, value); } return ret; }
有的时候,需要通过泛型指定函数的 返回值,比如:
public <T> T post(String url, String jsonString, Class<T> targetClass) throws BaseException { //OkHttpClient client = OkHttpUtils.getInstance().getUnsafeOkHttpClient(); OkHttpClient client = getUnsafeOkHttpClient(); RequestBody body = RequestBody.create(jsonType, jsonString); Request req = new Request.Builder() .url(url) .post(body) .build(); Response response = null; String ret = null; T r = null; try { response = client.newCall(req).execute(); if (response.isSuccessful()) { ret = response.body().string(); r = JSON.parseObject(ret, (Type) targetClass); log.error("r==>" + r); return r; } } catch (Exception e) { log.error("OkHttp.post Exception :{} ", e.getMessage()); e.printStackTrace(); throw new BaseException(e.getMessage(), e); } finally { response.close(); } return null; }
2. 类的泛型