简体   繁体   中英

Create generic list, whereby type of the list known only at runtime

I want to generate a generic list where the type of the list is known only at runtime (its the type of the object, which create that list).

Complete description:

I want to implement this functionality in a abstract class, so i know the parent class before runtime.

Don't know how to do that.

    Class myClass = getClass().getSuperclass();
    LinkedList<myClass> list = new LinkedList<myClass>();

does not work. Any ideas?

或者你可以写:

    List<Object> list = new LinkedList<Object>();

Generics are largely a compile time feature so it doesn't have any meaning in this context.

You can just write

List list = new LinkedList();

I usually prefer ArrayList if you can use that. ;)

Simply use Non-Generics ArrayList

ArrayList arrList = new ArrayList();

even you can use the <?>

Thought using the List will be good, as it show the principle of "Program in Interface rather than implementation"

Another option would be to parametrize the abstract class with the type of the extending class. This is a bit over-engineered, but should work:

package test;

import java.util.ArrayList;
import java.util.List;

public class  AbstractListHolder<T> {

    private List<T> list = new ArrayList<T>();

    List<T> getList() {
        return list;
    }

}

class ListHolder extends AbstractListHolder<ListHolder> {

    void doSomething() {
        getList().add(this);        
    }

}

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