Joel
Joel

Reputation: 95

Checking method template parameter type

I have the following method:

<T> String getBeanStrategyName(Store baseStoreModel, T clazz) {
    if (clazz instanceof PointsStrategy) {
        return baseStoreModel.getPointsStrategy();
    } else if (clazz instanceof RedemptionStrategy) {
        return baseStoreModel.getRedemptionStrategy();
    } else {
        return baseStoreModel.getPointsStrategy();
    }
}

However when I call the method like this getBeanStrategyName(store,PointsStrategy.class), the check clazz instanceof PointsStrategy returns false. I need somehow to check the passsed type and based on it return particular strategy

Upvotes: 0

Views: 54

Answers (1)

camilajenny
camilajenny

Reputation: 5034

PointsStrategy.class is of type java.lang.Class, not PointsStrategy so it rightfully returns false.

You can check it using

clazz.equals(PointsStrategy.class)

and btw it's better to declare the parameter as Class<?> to have a clearer contract,

String getBeanStrategyName(Store baseStoreModel, Class<?> clazz)

Upvotes: 1

Related Questions