首页 > 解决方案 > 通过注解对方法的数组列表(反射 Java)进行排序

问题描述

我正在尝试对方法反射的arrayList 进行排序,但我不知道如何声明比较函数。

我在每个方法上添加了一个注释,但是当我调用 Collections.sort() 它告诉我

Error:(222, 16) java: no suitable method found for sort(java.util.List<java.lang.reflect.Method>)
    method java.util.Collections.<T>sort(java.util.List<T>) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: java.lang.reflect.Method
        upper bound(s): java.lang.Comparable<? super java.lang.reflect.Method>)
    method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

这是我的代码:

推荐表格.java

public class test {

  @SortedMethod(3)
  public String[] getIssueRef() {
    return issueRef;
  }

  @SortedMethod(2)
  public String[] getAudRef() {
    return audRef;
  }

  @SortedMethod(1)
  public String[] getCradat() {
    return cradat;
  }


  @SortedMethod(4)
  public String[] getPriority() {
    return priority;
  }

  @SortedMethod(5)
  public String[] getStatus() {
    return status;
  }

}

排序方法.java:

public @interface SortedMethod{

  int value();



}

我的功能:

Method methods[] = ReflectionUtils.getAllDeclaredMethods(RecommendationForm.class);

    List<Method> getters = new ArrayList<Method>();

    for (int i = 0; i < methods.length; i++) {
      if ((methods[i].getName().startsWith("get")) && !(methods[i].getName().equals("getClass"))) {
        getters.add(methods[i]);
        //System.out.println(methods[i].toString());
      }
    }
    Collections.sort(getters);

谢谢你 !

我通过添加比较器方法解决了我的问题:

Collections.sort(getters, new Comparator<Method>() {
      @Override
      public int compare(Method o1, Method o2) {
        if(o1.getAnnotation(SortedMethod.class).value() > o2.getAnnotation(SortedMethod.class).value()){
          return 1;
        }
        else{
          return -1;
        }
      }
    });

标签: javaspringhibernatereflection

解决方案


您需要将RUNTIME保留策略添加到您的注释中,否则它会在编译后被删除:

@Retention(RetentionPolicy.RUNTIME)
@interface SortedMethod {
    int value();
}

value然后您可以通过比较注释的字段进行排序,例如:

List<Method> sorted = Arrays.stream(Test.class.getDeclaredMethods())
    .filter(m -> m.getAnnotation(SortedMethod.class) != null) // only use annotated methods
    .sorted(Comparator.comparingInt(m -> m.getAnnotation(SortedMethod.class).value())) // sort by value
    .collect(Collectors.toList());

System.out.println(sorted);

推荐阅读