文章目录
AnnotationAwareOrderComparator简介:
AnnotationAwareOrderComparator是OrderComparator的子类,用来支持Spring的Ordered类、@Order注解和@Priority注解。
源码解析
public class AnnotationAwareOrderComparator extends OrderComparator { // 对外提供的共享实例 public static final AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator(); /** * 用来检查实现Ordered接口、@Order和@Priority注解 */ protected Integer findOrder(Object obj) { // 检查常规的Ordered接口,通过子类重写的getOrder方法返回顺序值 Integer order = super.findOrder(obj); if (order != null) { return order; } // 检查实现@Order和@Priority注解 if (obj instanceof Class) { // 在类上检查@Order和@Priority注解,并找出顺序值 return OrderUtils.getOrder((Class<?>) obj); } else if (obj instanceof Method) { // 在方法上检查@Order注解,并找出顺序值 Order ann = AnnotationUtils.findAnnotation((Method) obj, Order.class); if (ann != null) { return ann.value(); } } else if (obj instanceof AnnotatedElement) { // 在注解中找@Order注解,并找出顺序值 Order ann = AnnotationUtils.getAnnotation((AnnotatedElement) obj, Order.class); if (ann != null) { return ann.value(); } } else if (obj != null) { order = OrderUtils.getOrder(obj.getClass()); if (order == null && obj instanceof DecoratingProxy) { order = OrderUtils.getOrder(((DecoratingProxy) obj).getDecoratedClass()); } } return order; } /** * 找Priority值 */ public Integer getPriority(Object obj) { Integer priority = null; if (obj instanceof Class) { priority = OrderUtils.getPriority((Class<?>) obj); } else if (obj != null) { priority = OrderUtils.getPriority(obj.getClass()); if (priority == null && obj instanceof DecoratingProxy) { priority = OrderUtils.getOrder(((DecoratingProxy) obj).getDecoratedClass()); } } return priority; } public static void sort(List<?> list) { if (list.size() > 1) { Collections.sort(list, INSTANCE); } } public static void sort(Object[] array) { if (array.length > 1) { Arrays.sort(array, INSTANCE); } } public static void sortIfNecessary(Object value) { if (value instanceof Object[]) { sort((Object[]) value); } else if (value instanceof List) { sort((List<?>) value); } } }