java 泛型类型判断

场景:在工厂中获取不同类型的对象,工厂输出对象具有相同的业务场景(例:输出环境== 工厂输出 -> 输入设备(泛型);使用环境== 轮训输入设备,找到 键盘这个类型的输入设备 (多个))

public static  T getSdk(Factory factory, DeviceSdkDto sdkDto,Class requireType) throws TypeMismatchException {
        DeviceSdk deviceSdk = factory.getSdk(sdkDto);
        if(instanceofFunc(deviceSdk,requireType)){
//        if(deviceSdk.getClass().equals(requireType)){
            return (T) deviceSdk;
        }else {
            throw new TypeMismatchException();
        }
    }

   private static  boolean instanceofFunc(Object obj,Class b){
        boolean result;
        if (obj == null) {
            result = false;
        } else {
            try {
                T temp=b.cast(obj);
//                T temp= (T) obj; // checkcast
                result = true;
            } catch (ClassCastException e) {
                result = false;
            }
        }
        return result;

    }

你可能感兴趣的:(java 泛型类型判断)