I’m trying to come up with a function that lets me pass in any object and a default value, and if the object cannot be casted to the type of the default value, it should return that default value. If the object is null, it should also return the default value.
It should be used like this:
Integer myVar = ConversionHelper.initialize( "123", 0 ) // should return Integer(123)
Integer myVar = ConversionHelper.initialize( "hello", 0 ) // should return Integer(0)
and so on
I tried with the following code:
public static <T> T initialize(Object o, T def) {
T ret;
try {
ret = (T) o;
} catch (Exception e) {
ret = def;
}
return ret==null ? def : ret;
}
but it fails with basic conversions, like casting an Integer to a String.
EDIT: took many of the suggestions from the answers, and now I’m looking for a way to do it without the series of if.. elseif… elseif and the try catch block that appears in my answer
Wildcards are only valid as type parameters, not as types. In this case, as you noticed, plain old
Objectis just as good.Another valid signature would be:
But this looks to be unnecessary in your case, since the generic types are unbounded.
As for your strategy of conversion using casting within a try/catch, I’m not sure about it. Someone else should weigh in on that part.
EDIT: as you’ve discovered, casting is very limited when it comes to all but the simplest conversions of data. You may need to implement mappings to the appropriate parsing method calls depending on the in and out types.
EDIT2: as an example of what you’re facing, here is a data conversion method somebody wrote for a project I’m on:
Note that this is only for mapping
StringtoT, where you want to mapT1toT2. Is there a better way? Maybe. Can SO help you find the right strategy? Of course, but the ball’s in your court to ask the right questions.EDIT3: Apache Commons’ beanutils.converters might be of help. I haven’t tried it out though, so I can’t remark on it.