Foredoomed
Foredoomed

Reputation: 2239

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.

Upvotes: 0

Views: 209

Answers (2)

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).

Upvotes: 1

Willem Mulder
Willem Mulder

Reputation: 13994

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.

Upvotes: 2

Related Questions