简体   繁体   English

如何在静态方法中返回泛型类型对象

[英]How to return a generic type object in a static method

i have 2 classes: 我有2节课:

public class Super {

    public static <T> T bar(Class<T> clazz){

        try {
            return (T)(clazz.newInstance());
        } catch (IllegalAccessException e) {           
            e.printStackTrace();
        } catch (InstantiationException e) {           
            e.printStackTrace();
        }
        return null;
    }
}

and

public class Sub extends Super{

    public static void main(String[] args){
        Sub s = Sub.bar(Sub.class);

    }
}

now i don't want to use Class<T> clazz as a param of bar , so how can i return the generic type T , thanks. 现在我不想将Class<T> clazz用作bar的参数,所以我如何返回通用类型T ,谢谢。

You can't. 你不能 Generics are only compile-time and are not available run-time. 泛型仅在编译时提供,在运行时不可用。 Thus, you'll have to provide the Class clazz in order to know the T at runtime. 因此,你必须提供Class clazz ,以了解在运行时的吨。

There is nothing wrong to providing Class instance to create new object. 提供Class实例来创建新对象没有错。

If your code require to create objects or generally operate on some Class, instance should be passed. 如果您的代码需要创建对象或通常在某个Class上进行操作,则应传递实例。 This action do not differ from other object usage. 此操作与其他对象用法没有区别。 The generics should make things easier and assure type safety. 泛型应该使事情变得更容易并确保类型安全。 So in this case the could be used only as a limitation on witch class could be created by bar static method, by setting some restriction on the generic parameter. 因此,在这种情况下,只能通过限制静态参数(通过对通用参数设置一些限制)来创建对女巫类的限制。

BTW. 顺便说一句。

You should call the static method from the class where the are implemented so instead of Sub.bar(Sub.class) you should have Super.bar(Sub.class) . 你应该叫从那里来实现的,而不是如此类的静态方法Sub.bar(Sub.class)你应该有Super.bar(Sub.class)

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

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