David Corsalini
David Corsalini

Reputation: 8208

Convert List<E> to List<T>, where T is abstract

I'm trying to generalize a method that I'll need to call a lot. It takes a List<E extends RealmObject> and return a List<T extends Pojo<E>>. The conversion from E to T is done via

new T().fromRealm(realmObject)

It won't work because T is an abstract class, so I can't instantiate it.

public static <E extends RealmObject, T extends Pojo<E>> List<T> fromRealmList(
        RealmList<E> realmList) {
    List<T> pojoObjects = new ArrayList<>();
    if (realmList != null) {
        for (E realmObject : realmList) {
            try {
                pojoObjects.add(new T().fromRealm(realmObject));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return pojoObjects;
}

I also tried with this answer, but List<T> won't accept the object created with clazz.newInstance().

EDIT: adding Pojo class

public abstract class Pojo<R extends RealmObject> {

@NonNull
public abstract R toRealm();

@NonNull
public abstract Pojo<R> fromRealm(R realmObject);
}

EDIT2: adding an alternate solution, that still doesn't work: Required T, found Pojo<E>.

T newInstance = clazz.getConstructor()
                     .newInstance()
                     .fromRealm(realmObject);
                pojoObjects.add(newInstance);

Upvotes: 0

Views: 135

Answers (1)

geert3
geert3

Reputation: 7321

Apart from being an abstract class, T is also a parameter type, which cannot be used in a constructor new T().

A typical solution would be to use reflection:

  • pass an additional parameter Class<T> clazz to your method fromRealmList
  • invoke clazz.getConstructor(...).newInstance(...)

Maybe not perfect but that should work.

--edit-- The below is an example without using type T:

public static <E extends RealmObject> List<Pojo<E>> fromRealmList(
    RealmList<E> realmList, Class<Pojo<E>> clazz) {

   List<Pojo<E>> pojoObjects = new ArrayList<>();
   ...
   Pojo<E> newInstance = clazz.getConstructor(...).newInstance(...).fromRealm(...);
   pojoObjects.add(newInstance);
   ...
}

Upvotes: 1

Related Questions