简体   繁体   中英

How to return a generic type object in a static method

i have 2 classes:

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.

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.

There is nothing wrong to providing Class instance to create new object.

If your code require to create objects or generally operate on some Class, instance should be passed. 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) .

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