instanceof & instance & isAssignableFrom总结

Java类型判断实例:instanceof、Class.instance()、Class.isAssignableFrom()解析
本文详细解析Java中用于判断对象或类类型的三种方法:instanceof、Class.instance()、Class.isAssignableFrom。通过实际例子展示了它们的功能差异,并引用了传智播客黎活明老师的视频讲解。文章最后提供了StackOverflow上的深入讨论链接,供读者进一步学习。

说明:

本系列博客是本人在工作中遇到的一些问题的整理,其中有些资料来源网络博客,有些信息来自出版的书籍,掺杂一些个人的猜想及验证,总结,主要目的是方便知识的查看,并非纯原创。本系列博客会不断更新。原创不容易,支持原创。对于参考的一些其他博客,会尽量把博客地址列在博客的后面,以方便知识的查看。

 

instanceofClass.instance()Class.isAssignableFrom()三者的基本功能是一样的,都是用于判断一个对象或类是否是某种类型,不同的表述,不同的形式而已,在一些细节上可能有点差异。一般用于框架抽象,像接口、实现类比较丰富,或类继承层次比较多的场景。在传智播客黎活明老师讲解的《巴巴运动网》视频,对通用DAO抽象的时候使用到了isAssignableFrom,感兴趣的可以看下。

 

更多的讨论可以参看stackoverflow上的讨论:

http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom

* @see Observe */ public static RequestExecuteMetadata createRequest(@NotNull Method method, @Nullable Object[] args) { Request<?> request = null; //create request. List<Callback> callbacks = new ArrayList<>(); //parameter callbacks. ThrowablePredicate throwablePredicate = null; AsyncPubSubExecutorProvider executorProvider = null; Executor subscriptionExecutor = null; Executor observeExecutor = null; Map<String, Pair<Boolean, Object>> setterMetadata = new HashMap<>(); //support setter data. /* * When the parameter does not provide the type of Request, * find the annotation for the method. * */ if (args == null) { RequestType requestType = method.getAnnotation(RequestType.class); if (requestType == null) { throw new UnknownRequestParameterException(); } request = ReflectUtil.instantiates(requestType.value()); } else { //First, filter to see if there are any Request instances. List<Object> requestInstances = Arrays.stream(args) .filter(r -> r instanceof Request).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(requestInstances)) { if (requestInstances.size() > 1) throw new UnknownRequestParameterException(); //Only one request can exist. request = (Request<?>) requestInstances.get(0); } //the reflection creation type when there is no request for the parameter. Class<? extends Request> requestType = null; //support for RequestConstructor annotation as constructor args. //Arrange the construction parameter groups in the order provided by the annotations. SortedMap<Integer, Object> constructorArgs = null; if (request == null) constructorArgs = new TreeMap<>();//Initialize only when no instance exists. Parameter[] parameters = method.getParameters(); for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) continue; // null filter continue. if (arg instanceof Request) continue;//It has been resolved in the above steps. /* * Support type 1: Retrieve the type of Request from a specific interface * and support subsequent parsing. */ if (arg instanceof RequestTypeSupplier && request == null) { Class<? extends Request> rt = ((RequestTypeSupplier) arg).getRequestType(); if (requestType == null) { requestType = rt; } else { if (!Objects.equals(requestType, rt)) { throw new UnknownRequestParameterException(); } } } Parameter parameter = parameters[i]; /* * Support type 2: Callback type parameter parsing, supporting object instance, * collection, array and other types for subsequent parsing. */ if (arg instanceof Callback) { callbacks.add((Callback) arg); } else if (arg instanceof Collection) { //2-arg-collection-1: all of them are Callback elements. if (((Collection<?>) arg).stream().allMatch(c -> c instanceof Callback)) { callbacks.addAll((Collection<? extends Callback>) arg); } } else if (arg.getClass().isArray()) { //2-arg-array-1: all of them are Callback elements. if (Callback.class.isAssignableFrom(arg.getClass().getComponentType())) { for (Object o : ArrayUtils.toArray(arg)) { callbacks.add((Callback) o); } } } /* * Support type 3: Support annotation RequestConstructor parsing, provided that * the parameter array does not have a Request instance. */ if (request == null && parameter.isAnnotationPresent(RequestConstructor.class)) { RequestConstructor requestConstructor = parameter.getAnnotation(RequestConstructor.class); if (requestConstructor.required()) { constructorArgs.put(requestConstructor.order(), arg); } } /* * Support type 4:Support annotation RequestSetter parsing, perform set related * assignment after obtaining the Request instance. */ if (parameter.isAnnotationPresent(RequestSetter.class)) { RequestSetter requestSetter = parameter.getAnnotation(RequestSetter.class); String name = requestSetter.name(); if (StringUtils.isBlank(name)) name = parameter.getName(); setterMetadata.put(name, Pair.create(requestSetter.useReflect(), arg)); } /* * Support type 5:Support parsing the first {@code ThrowablePredicate} instance * object from parameters. */ if (throwablePredicate == null && arg instanceof ThrowablePredicate) { throwablePredicate = (ThrowablePredicate) arg; } /* * Support type 6:Support parsing the first {@code AsyncPubSubExecutorProvider} instance * object from the parameters, or the subscriber {@code Executor} instance object marked * with annotation {@code Subscription}, or the observer {@code Executor} instance object * marked with annotation {@code Observe}. */ if (executorProvider == null && arg instanceof AsyncPubSubExecutorProvider) { executorProvider = (AsyncPubSubExecutorProvider) arg; } if (executorProvider == null && (subscriptionExecutor == null || observeExecutor == null) && arg instanceof Executor) { if (parameter.isAnnotationPresent(Subscription.class)) { subscriptionExecutor = (Executor) arg; } else if (parameter.isAnnotationPresent(Observe.class)) { observeExecutor = (Executor) arg; } } } //After the loop ends, initialize using the type based on whether // the request instance exists. if (request == null) { if (requestType == null) { RequestType annotation = method.getAnnotation(RequestType.class); if (annotation == null) { throw new UnknownRequestParameterException(); } requestType = annotation.value(); } if (constructorArgs.isEmpty()) { request = ReflectUtil.instantiates(requestType); } else { request = ReflectUtil.instantiates(requestType, constructorArgs.values().toArray()); } } } //Finally, perform set support assignment on the instantiated request instance. if (!setterMetadata.isEmpty()) { for (Map.Entry<String, Pair<Boolean, Object>> entry : setterMetadata.entrySet()) { String name = entry.getKey(); Pair<Boolean, Object> assignmentInfo = entry.getValue(); Object value = assignmentInfo.getSecond(); if (assignmentInfo.getFirst()) { ReflectUtil.setFieldValue(request, name, value); } else { executeSetMethod(request, request.getClass(), name, value); } } } return new ParameterResolveRequestExecuteMetadata(request, method, callbacks, throwablePredicate, executorProvider != null ? executorProvider : (subscriptionExecutor != null || observeExecutor != null) ? new AsyncPubSubExecutorProviderImpl(subscriptionExecutor, observeExecutor) : null); } 你觉得写的怎么样? 是否可以优化?
最新发布
11-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值