简体   繁体   English

Java:抽象通用数据上下文 class

[英]Java: Abstract generic data context class

I would like to store all application data in a data context class.我想将所有应用程序数据存储在数据上下文 class 中。

Having application data classes A and B implementing IApplicationData , the non-abstract, non-generic version could look like this:让应用程序数据类AB实现IApplicationData ,非抽象、非通用版本可能如下所示:

NonGenericDataContext非通用数据上下文

private List<A> aList;
private List<B> bList;

public List<A>getAs() {
    return aList;
}

public List<B>getBs() {
    return bList;
}

Now I would like to abstract from the concrete application classes and use a generic data context to use common functionality in multiple applications.现在我想从具体的应用程序类中抽象出来,并使用通用数据上下文在多个应用程序中使用通用功能。 The data context class could then look like this:数据上下文 class 可能如下所示:

AbstractGenericDataContext抽象通用数据上下文

protected Map<Class<? extends IApplicationData>, List<? extends IApplicationData>> listsByType;

public List<? extends IApplicationData> getListByType(Class<? extends IApplicationData> clazz) {
    return objectListsByType.get(clazz);
}

I would love to use proper generics, but Java erases the type during compilation, hence the construct with Class .我很想使用正确的 generics,但 Java 在编译期间会擦除类型,因此使用Class的构造。 Unfortunately, the construct above makes the code cumbersome and return values of getListByType() need to be casted.不幸的是,上面的构造使代码变得繁琐,并且需要getListByType()的返回值。

Question How could the code be improved to achieve an abstract, generic (not necessarily in a JLS sense, but with similar usability) data context class?问题如何改进代码以实现抽象的通用(不一定在 JLS 意义上,但具有类似的可用性)数据上下文 class?

I would like stick with a pure Java solution (so no code generators if possible).我想坚持使用纯 Java 解决方案(所以如果可能的话,不要使用代码生成器)。 Reflection would be ok if it does not slow down data access in a critical way.如果反射不会以关键方式减慢数据访问速度,那么反射是可以的。

You have to parameterize your generic function (the class doesnt't have to be abstract for that):您必须参数化您的通用 function ( class 不必是抽象的):

public class GenericContext {

    protected Map<Class<? extends IApplicationData>, List<? extends IApplicationData>> listsByType = new HashMap<>();

    public <T extends IApplicationData> List<T> getListByType(Class<T> clazz) {
        return (List<T>) listsByType.get(clazz);
    }

    public static void main(String[] args) {
        GenericContext context = new GenericContext();

        context.listsByType.put(ApplicationData.class, Arrays.asList(new ApplicationData()));
        context.listsByType.put(ApplicationData2.class, Arrays.asList(new ApplicationData2()));

        List<ApplicationData> list = context.getListByType(ApplicationData.class);
        System.out.println(list);
    }
}

Output Output

[ApplicationData@5ca881b5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM