I am building a java class to be used as a generic comparator based on the sample shown on Generic Comparator. The constructor I am building for the comparator is as follows:
public GenericComparator(java.lang.reflect.Field sortField, boolean ascending){
.... }
While the above constructor allows me to get the sort field, there is no way for the compiler to know if the field is implementing Comparable interface and a developer calling the constructor may pass a field that doesn’t implement the Comparableinterface.
I am wondering if there is a way to make this a compile time error and not handle it at Run time with the use of instanceof check to make sure the field has implemented the interface.
A similar implementation found in the Collections.sort(...) Type declaration.
public static <T extends Comparable<? super T>> void sort(List<T> list) {
...
}
does it at runtime, but there’s no way at all to make this a compile-time error. Fields don’t (and can’t, really) carry their type information at compile time — they’re runtime objects, and can be chosen at runtime. For example, if you had
then no compiler, no matter how smart, could tell at compile time what type the resulting field would have.