简体   繁体   中英

Create instance of class or superclass from generic type

I'm new in Java. I'm developing program for Android similar to app for iOS. One of the purposes of app - is get data from server. Data often is array with dictionaries like "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():

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

It works, but for sublass of BaseItem -it doesn't work. 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:

new BaseArrayList<SomeSublassOfBaseItem>

This issue resolved in ObjC like this -

[[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:

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 . 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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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