I have the following code,
public <T> T build(Object source, Class<T> destClass) {
if((Object)destClass instanceof TestDTO){
return (T) testBuilder.build((BlahDTO) source);
}
if((Object)destClass instanceof BestDTO) {
return (T) bestBuilder.build((BlahDTO) source);
}
return null;
}
I am trying to compare if the destClass if either of the type TestDTO or BestDTO and take the appropriate action. But the comparison fails even though the destClass is of the specified type. Am I missing something, also my alternate approach,
public <T> T build(Object source, Class<T> destClass) {
if(destClass.getSimpleName().equals(TestDTO.class.getSimpleName())){
return (T) testBuilder.build((BlahDTO) source);
}
if(destClass.getSimpleName().equals(BestDTO.class.getSimpleName())) {
return (T) bestBuilder.build((BlahDTO) source);
}
return null;
}
although this approach works, I find this code a bit dicey. It would be helpful if someone pointed out what I was doing wrong, or suggest an alternate approach. Thanks in advance!
instanceof
checks to see if the left-hand operand is an instance of the right-hand operand. But your left-hand operand is a Class
object, not an instance of that class. To use instanceof
, you must have an instance of the class (something created via new TheClass
).
As Thomas points out, if you really mean to be working with Class
instances, you may want isAssignableFrom
instead:
if (TestDTO.class.isAssignableFrom(destClass))
Side note: There's no purpose served by the (Object)
cast on if((Object)destClass instanceof TestDTO)
. instanceof
checks the object, not the kind of reference you have to it; casting is irrelevant to that check.