SR2 :
I am trying to make a function that re returns a comparator on a field of a class, but I am getting an error when I am trying to get the value of o2, at the line Comparable v2 = (Comparable) field.get(o2);
, saying that a lambda parameter cannot be converted to an object. Can someone help?
public Comparator comp(String className, String fieldName) throws Exception {
Comparator comparator = Comparator.comparing((o1, o2) -> {
Class aClass = null;
try {
aClass = Class.forName(className);
Field field = aClass.getDeclaredField(fieldName);
field.setAccessible(true);
Comparable v1 = (Comparable) field.get(o1);
Comparable v2 = (Comparable) field.get(o2);
return v1.compareTo(v2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
});
return comparator;
}
Joni :
You're using a Comparator.comparing method, but what you're passing in is actually an implementation of a comparator. You could just get rid of that method call and use:
Comparator comparator = (o1, o2) -> {
Class aClass = null;
try {
aClass = Class.forName(className);
Field field = aClass.getDeclaredField(fieldName);
field.setAccessible(true);
Comparable v1 = (Comparable) field.get(o1);
Comparable v2 = (Comparable) field.get(o2);
return v1.compareTo(v2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
};
return comparator;
Alternatively you could keep using the Comparator.comparing method, but keep in mind that you're supposed to pass in a function that extracts the value of a field:
public Comparator comp(String className, String fieldName) throws Exception {
Class aClass = Class.forName(className);
Field field = aClass.getDeclaredField(fieldName);
field.setAccessible(true);
Comparator comparator = Comparator.comparing(o1 -> {
try {
Comparable v1 = (Comparable) field.get(o1);
return v1;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
});
return comparator;
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=349368&siteId=1