I call the method by reflection, and its return type is generic. I do not want the return value to be null, so in this case I want to assign a default value to this generic type .
That is, after calling the method by reflection, I would like to execute something like this:
T resultNotNull = (T) reflectionMethodThatCanReturnNull.invoke(anObject); // If it null, let assign something assignable. if (resultNotNull == null) { if (resultNotNull.getClass().isAssignableFrom(Long.class)) { resultNotNull = (T) Long.valueOf(-1); } else if (resultNotNull.getClass().isAssignableFrom(String.class)) { resultNotNull = (T) "NOTHING"; } }
But, of course, if 'resultNotNull == null', we cannot call 'resultNotNull.getClass ()' without getting an exception.
Any ideas on how to assign a default value depending on the type of the generic type?
All code will look something like this:
public class ReflectionTest { public class Class1ok { public Long method () { return Long.valueOf(1); } } public class Class1null { public Long method () { return null; }
source share