Peter
Peter

Reputation: 11890

Dynamic cast to generic type in Java

Here is a trivial example I have put together:

private static <T> T getValue(T defaultValue) {
    if (defaultValue instanceof Boolean) {
        return (T) true;
    }
    return defaultValue;
}

Essentially, I wish to return "true" if T is of boolean type. However, I get a compile error that boolean cannot be cast to T.

How do I do it?

Also, is there a way to check if T is of type boolean? Regards.

Upvotes: 2

Views: 1458

Answers (2)

jakub.petr
jakub.petr

Reputation: 3031

true is a primitive type and you want to return an Object. You should wrap true in an object.

This works:

private static <T> T getValue(T defaultValue) {
    if (defaultValue instanceof Boolean) {
        return (T)Boolean.valueOf(true);
    }
    return defaultValue;
}

Upvotes: 5

EJK
EJK

Reputation: 12527

Change

        return (T) true;

To

        return (T) Boolean.TRUE;

This will work as Boolean.True is an instance of class Boolean. The value "true" is of the primitive type boolean.

Upvotes: 7

Related Questions