I'm trying to sort an arrayList of methods reflection , but I don't know how to declare the compare function.
I added an annotation on each of my methods but when I call Collections.sort() it tells me that
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))
Here is my code :
RecommendationForm.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;
}
}
SortedMethod.java:
public @interface SortedMethod{
int value();
}
And my Function :
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);
Thank You !
I've solved my problem by adding a comparator method :
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;
}
}
});