简体   繁体   English

创建通用列表,从而仅在运行时知道列表的类型

[英]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. 如果可以使用的话,我通常更喜欢ArrayList。 ;) ;)

Simply use Non-Generics ArrayList 只需使用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" 使用List想法会很好,因为它显示了"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);        
    }

}

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

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