简体   繁体   English

如何在Java中将类型传递给泛型类?

[英]How can I pass a Type to a generic Class in java?

everyone here! 大家在这里! I want pass a Type to a generic Type, like Arraylist, how can I do this? 我想将类型传递给通用类型,例如Arraylist,该怎么做? I make a simple Example, so that you will know what I want, of course this code is wrong. 我做一个简单的示例,以便您知道我想要什么,当然此代码是错误的。

public static void passObjType(Object obj) {

    Class clazz = obj.getClass();

    ArrayList<clazz> arr = new ArrayList<clazz>();

}

public static void main(String[] args) {

    HashSet<String> hs = new HashSet<String>();

    passObjType(hs);
}

I hope, if I input a HashSet object, the funktion PassObjType() will create a Arraylist with HashSet and If I input a String Object, then it will create a Arraylist with String. 我希望,如果我输入一个HashSet对象,则功能PassObjType()将使用HashSet创建一个Arraylist,如果我输入一个String对象,则它将创建一个具有String的Arraylist。 How can I do this? 我怎样才能做到这一点?

You can try something like 您可以尝试类似

public static <T> void passObjType(T obj) {
    ArrayList<T> arr = new ArrayList<T>();
    //...
}

public static void main(String[] args) {
    HashSet<String> hs = new HashSet<String>();
    passObjType(hs);
}

But I am not sure if that is what you want since at runtime generic types are erased and ArrayList<String> is just ArrayList (which can store any Object). 但是我不确定这是否是您想要的,因为在运行时会删除通用类型,并且ArrayList<String>只是ArrayList (可以存储任何对象)。

You can use Java Generics to get the parameter of Object type, as below : 您可以使用Java泛型来获取对象类型的参数,如下所示:

        public static<T> void passObjType(T e) {
             ArrayList<T> arr = new ArrayList<T>();
        }

        public static void main(String[] args) {
            HashSet<String> hs = new HashSet<String>();
            String hp = new String();
            passObjType(hs);
            passObjType(hp);
        }

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

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