获取泛型的实际类型

package com.example.net;

import androidx.lifecycle.Observer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class TestType {

    /**
     * 获取泛型的实际类型
     *
     * @param object 如 Result
     * @return Type
     */
    public static Type getType(Object object) {
        Type type = null;
        try {
            Type[] interfaceTypes = object.getClass().getGenericInterfaces();
            if (interfaceTypes.length == 0) {
                //非接口
                type = object.getClass().getGenericSuperclass();
            } else {
                //接口
                type = interfaceTypes[0];
            }
            if (type != null) {
                if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
                    type = (((ParameterizedType) type).getActualTypeArguments())[0];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return type;
    }

    public static void main(String[] args) {
        NetRequest netRequest = new NetRequest();
        netRequest.observer = new Observer>>() {
            @Override
            public void onChanged(NetResult> netResult) {

            }
        };
        netRequest.netCallback = new NetCallback>>() {
            @Override
            public void callback(NetResult> netResult) {

            }
        };
        NetCallback2 netCallback2 = new NetCallback2() {
            @Override
            public void callback() {

            }
        };
        List> list1 = new ArrayList>();
        List> list2 = new ArrayList>() {
        };
        System.out.println("getType : " + getType(list1));
        System.out.println("getType : " + getType(list2));
        System.out.println("getType : " + getType(netRequest.observer));
        System.out.println("getType : " + getType(netRequest));
        System.out.println("getType : " + getType(netCallback2));
        System.out.println("getType : " + String.class.getCanonicalName());
        System.out.println("getType : " + getType(new Object()));
    }

}

getType : E
getType : java.util.List
getType : com.example.net.NetResult>
getType : class java.lang.Object
getType : interface com.example.net.NetCallback2
getType : java.lang.String
getType : null

你可能感兴趣的:(获取泛型的实际类型)