简体   繁体   English

从泛型类型创建类或超类的实例

[英]Create instance of class or superclass from generic type

I'm new in Java. 我是Java新手。 I'm developing program for Android similar to app for iOS. 我正在为Android开发类似于iOS应用的程序。 One of the purposes of app - is get data from server. 应用程序的目的之一-是从服务器获取数据。 Data often is array with dictionaries like "id = 1", "name = SomeName". 数据通常是带有字典的 数组 ,例如“ id = 1”,“ name = SomeName”。 I've class 我上课了

class BaseArrayList<Type extends BaseItem> extends BaseItem {

public void processObject(Map<?,?> map) {
     //......
     //Some loop body
     Type item =  (Type) Type.create();
     item.processObject(map);
     //.....
}

Also BaseItem have method create(): BaseItem也有方法create():

public static BaseItem create() {
    return new BaseItem();
}

It works, but for sublass of BaseItem -it doesn't work. 它可以工作,但是对于BaseItem子集-不起作用。 I found that static methods are not overriding. 我发现静态方法没有覆盖。

So, how I can resolve this task: create custom class in array with just creating custom instances of BaseArrayList such as: 因此,我如何解决此任务:仅创建BaseArrayList的自定义实例即可在数组中创建自定义类,例如:

new BaseArrayList<SomeSublassOfBaseItem>

This issue resolved in ObjC like this - 这样的问题在ObjC中得以解决-

[[memberClass alloc] init];

I found that static methods are not overriding. 我发现静态方法没有覆盖。

Indeed, overriding does not work for static methods. 实际上,对于静态方法而言,覆盖无效。

There are different ways to achieve what you want to do. 有多种方法可以实现您想要的。 One is to pass a Class<Type> object to your processObject method, which you can use to create instances of Type from by calling newInstance() on it: 一种是将Class<Type>对象传递给您的processObject方法,您可以通过在其上调用newInstance()从其创建Type实例:

public void processObject(Map<?, ?> map, Class<Type> cls) {
    // Uses the no-args constructor of Type to create a new instance
    Type item = cls.newInstance();

    // ...
}

Another more flexible way is to supply a factory to create instances of Type . 另一种更灵活的方法是提供工厂来创建Type实例。 A disadvantage of this is that you'd need to implement a factory for each subclass of BaseItem that you'd want to use for this. 这样做的一个缺点是,您需要为BaseItem每个子类实现一个工厂。

public interface Factory<T> {
    T create();
}

// ...

public void processObject(Map<?, ?> map, Factory<Type> factory) {
    // Calls the factory to create a new Type
    Type item = factory.create();

    // ...
}

// Factory implementation for BaseItem
public class BaseItemFactory implements Factory<BaseItem> {
    @Override
    public BaseItem create() {
        return new BaseItem();
    }
}

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

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