hridayesh
hridayesh

Reputation: 1143

Java: returning object of same class(which have common parent class) passed

I was doing something like below but it returns object of base class rather than subclass.

public static BaseVo getObject(String objID, Class<? extends BaseVo> cls) {
    BaseVo obj = constructObject(objID, cls);
    return obj;
}

Ofcourse actual obj is of subclass, I can easily typecast after returning. But I wanted to find a way so that every function do not have to typecast after calling getObject.

Upvotes: 0

Views: 91

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280181

Make the method generic.

public static <T extends BaseVo> T getObject(String objID, Class<T> cls) {
    T obj = constructObj(objID, cls);
    return obj;
}

This assumes that constructObj can be modified to return T as well.

Upvotes: 4

Related Questions