java - 通过注解对方法的数组列表(反射 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;
}
}
});
解决方案
您需要将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);
推荐阅读
- azure - Azure B2C 的自定义用户管理
- javascript - 如何在ejs中替换unicode
- c# - 415(不支持的媒体类型)Angular API 调用
- marko - MarkoJS 组件中“无法读取未定义的属性'insertInto'”错误的原因是什么?
- python - 如何向选定的用户发送邮件
- c# - 如何在 Code Xamarin Android 中设置 VerticalOptions、HorizontalOptions?
- powershell - 如何使用 Powershell 检查重复的文件名?
- javascript - 防止路由器出口默认属性
- django - 将进度返回到 Django 中每个值更改的模板
- flutter - 我是否在颤振应用程序中使用了正确的 .yaml 缩进?