有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中,如何获取作为泛型参数传递给函数的实体字段?

我有一个接收任何实体类的泛型方法。我的所有实体都有一个LocalDate类型的createDate字段。我想访问并获取泛型方法中的字段。方法是这样的

public static < T > List<Resource> printArray( List<T> entity) {
    for( T e : entity ) {
        LocalDate d = e.getCreateDate(); //Wrong
    }

我不想检查泛型参数的实例并对其进行类型转换,因为有很多实体,我希望代码是最小的(因此是泛型函数)。 我该怎么做


共 (3) 个答案

  1. # 1 楼答案

    您可以使用抽象方法getCreateDate()创建接口

    interface IDate {
        LocalDate getCreateDate();
    }
    

    假设您的所有实体都实现了此接口,则您的方法如下所示:

    public static <T extends IDate> List<Resource> printArray(List<T> entity) {
        for(T e : entity ) {
            LocalDate d = e.getCreateDate();
        }
    }
    

    否则,无法保证传递到此方法的实体具有方法getCreateDate()

    @VHS建议的反射解决方案

  2. # 2 楼答案

    可以使用反射调用泛型类型上具有给定名称的方法

        for( T e : entity ) {
            try {
                Method method = e.getClass().getMethod("getCreateDate");
                method.invoke(e);
            }
            catch(Exception e1) {
                e1.printStackTrace();
            }                       
        }
    
  3. # 3 楼答案

    当实体类型没有公共超类型来声明getCreateDate方法,并且无法更改类型层次结构时,必须使用委派:

    public static <T> List<Resource> printArray(
        List<? extends T> entities, Function<? super T, ? extends LocalDate> accessor) {
    
        for(T e: entities ) {
            LocalDate d = accessor.apply(e);
            // ...
        }
        // ...
    }
    

    这个方法可以像下面这样调用

    printArray(listOfEntities, EntityType::getCreateDate);
    

    其中EntityType表示列表的特定元素类型