lundi 10 juillet 2023

Lambda sort using Reflection

I'm working on a project that requires the use of sorted Class lists, and I have a lambda expression that worked according to the type of class I needed to be sorted. The sorting occurs on a date field of the class itself:

Comparator<Class1> comparatorDescending = (exp1, exp2) -> exp2.getDate().compareTo(exp1.getDate());
        this.classlist2sort.sort(comparatorDescending);

However I have two, maybe more classes that need to be sorted in this way and I decided to move the lambda expression above to the parent class and make it a generic. This required a bit of work however in that I now need to pass into the parent class the type of class I'm dealing with (Class1.class), condition on that, then sort with generic. I tried the following using Reflection:

Method m = this.typeParameterClass.getDeclaredMethod("getDate");

Comparator<T> comparatorDescending = (exp1, exp2) ->
                m.invoke(exp2).compareTo(m.invoke(exp1));
this.classlist2sort((Comparator<? super T>) comparatorDescending);

Doing so gave me an error message: Unhandled exceptions: java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException to which I followed the suggested workaround of surrounding the expression with a try catch in the following manner:

Method[] input = this.typeParameterClass.getDeclaredMethods();
Method m = this.typeParameterClass.getDeclaredMethod("getDate");

Comparator<T> comparatorDescending = (exp1, exp2) -> {
            try {
                return m.invoke(exp2).compareTo(m.invoke(exp1));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
this.classlist2sort((Comparator<? super T>) comparatorDescending);

Unfortunately, doin this resulted in a Cannot resolve method 'compareTo' in 'Object' error. I am wondering now if what I'm trying to do is possible. Any help is appreciated





Aucun commentaire:

Enregistrer un commentaire