尝试在Gradle项目中使用BeanComparator

but5z9lq  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(126)

我在gradle项目中使用BeanComparator时遇到问题。我可以在build.gradle中导入实现'commons-beanutils:commons-beanutils:1.9.4'
但是当我尝试导入commons-beanutils.commons.beanutils.BeanComparator时,我总是看到无法解析符号commons
有没有人有一个在import语句中使用BeanComparator的工作示例?使用BeanComparator不是一个好主意,因为它使用了反射?它似乎完全符合我的要求。
我已经尝试了多种变体导入commons-beanutils.commons-beanutils.BeanComparator导入commons.beanutils.commons-beanutils.BeanComparator等。
我也尝试过实现'org.apache.commons.beanutils:1.9.4',但它不存在

ggazkfy8

ggazkfy81#

在Gradle版本中

dependencies{
    // https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils
    implementation 'commons-beanutils:commons-beanutils:1.9.4'
    . . . 
}

在Java类文件中:

import java.util.Comparator;
import org.apache.commons.beanutils.BeanComparator;
...
    // Assume you want to compare Person objects based on their age properties.
    private Comparator<Person> bc = new BeanComparator<>("age");

Google“apache BeanComparator example”中有很多用法示例。
但我会用

people.sort((Person p1, Person p2)->p1.getAge()-p2.getAge());

例如

import java.util.Arrays;
import java.util.List;
import java.util.Comparator;
import org.apache.commons.beanutils.BeanComparator;

public class BeanComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(new Person("Bart", 28), new Person("Iris", 23), new Person("Dumsani", 71));

        people.sort((Person p1, Person p2) -> p1.getAge() - p2.getAge());
        System.out.println("Sort using comparator lambda: " + people);

        // I wouldn't use BeanComparator because you can do this in regular Java
        // without additional dependencies (and possible vulnerabilities),
        // and BeanComparator seems to be hostile to Java records.
        Comparator<Person> bc = new BeanComparator<>("name");
        people.sort(bc);
        System.out.println("Sort on name using BeanComparator: " + people);
    }

    public static class Person {
        private String name;
        private int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return this.name;
        }
        public int getAge() { 
            return this.age;
        }
        public String toString() {
            return "Person [" + name + ", " + age + "]";
        }
    }

}

另外,BeanComparator似乎不喜欢Java record

相关问题