场景:在工厂中获取不同类型的对象,工厂输出对象具有相同的业务场景(例:输出环境== 工厂输出 -> 输入设备(泛型);使用环境== 轮训输入设备,找到 键盘这个类型的输入设备 (多个))
public static <T extends DeviceSdk> T getSdk(Factory factory, DeviceSdkDto sdkDto,Class<T> 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 <T> boolean instanceofFunc(Object obj,Class<T> 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;
}