Dynamically cast to a generic type in Java

Here is a trivial example that I put together:

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

Essentially, I want to return "true" if T is of type boolean. However, I get a compilation error that boolean cannot distinguish from T.

How can I do it?

Also, is there a way to check if type T is type boolean? Best wishes.

+2
source share
2 answers

Edit

  return (T) true; 

For

  return (T) Boolean.TRUE; 

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

+5
source

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

It works:

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

Source: https://habr.com/ru/post/1272988/


All Articles