ServletParameterOrderIntrospector.java

package server.restful.common.parameter;

import com.beust.jcommander.Parameter;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ServletParameterOrderIntrospector extends JacksonAnnotationIntrospector {

    @Override
    public String[] findSerializationPropertyOrder(AnnotatedClass ac) {
        try {
            Class<?> type = ac.getRawType();

            if (type.isPrimitive()) {
                return null;
            }
            BeanInfo beanInfo = Introspector.getBeanInfo(type, Object.class);

            List<PropertyDescriptor> sorted = Arrays.stream(beanInfo.getPropertyDescriptors()).sorted(Comparator.comparingInt(this::getOrder).thenComparing(PropertyDescriptor::getName)).collect(Collectors.toList());

            return sorted.stream().map(PropertyDescriptor::getName).toArray(String[]::new);
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
    }

    private int getOrder(PropertyDescriptor pd) {
        try {
            Parameter annotation = null;

            // 1. setter (highest priority)
            if (pd.getWriteMethod() != null) {
                annotation = pd.getWriteMethod().getAnnotation(Parameter.class);
            }

            // 2. getter fallback
            if (annotation == null && pd.getReadMethod() != null) {
                annotation = pd.getReadMethod().getAnnotation(Parameter.class);
            }

            // 3. field fallback
            if (annotation == null) {
                Field field = pd.getReadMethod() != null ? pd.getReadMethod().getDeclaringClass().getDeclaredField(pd.getName()) : null;

                if (field != null) {
                    annotation = field.getAnnotation(Parameter.class);
                }
            }

            return annotation != null ? annotation.order() : -1;

        } catch (NoSuchFieldException | SecurityException e) {
            return -1;
        }
    }
}