java # generics

1. generic method

Sometimes a write method, it is necessary to accept various types of parameters, which can be used as the type Object, a method may be used generic parameter, the parameter T write, and write <T> in front of the return value is represented by generic, such as:

   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 right; 
    }

Sometimes, we need to return the value specified by the generic function, such as:

    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. Class generic

 

Guess you like

Origin www.cnblogs.com/luohaonan/p/11927236.html