Reputation: 31
In the end, I want to have something that does something similar to this, which I will use to search correct constructor for reflection.
public static boolean equalWithPrimitive(Class<?> from, Class<?> target){
if(from == target){
return true;
}else if((from == Byte.class || from == byte.class) && (target == Byte.class || target == byte.class)){
return true;
}else if((from == Short.class || from == short.class) && (target == Short.class || target == short.class)){
return true;
}else if((from == Integer.class || from == int.class) && (target == Integer.class || target == int.class)){
return true;
}else if((from == Long.class || from == long.class) && (target == Long.class || target == long.class)){
return true;
}else if((from == Float.class || from == float.class) && (target == Float.class || target == float.class)){
return true;
}else if((from == Double.class || from == double.class) && (target == Double.class || target == double.class)){
return true;
}else if((from == Boolean.class || from == boolean.class) && (target == Boolean.class || target == boolean.class)){
return true;
}else if((from == Character.class || from == char.class) && (target == Character.class || target == char.class)){
return true;
}
return false;
}
Is there a shorter and an accurate way to achieve this thought?
Upvotes: 3
Views: 81
Reputation: 35405
The most fool-proof way is to keep a Map of primitive->boxed type and use that for conversion before doing the check:
private static final Map<Class, Class> primitiveWrapperMap = new HashMap();
static {
primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
primitiveWrapperMap.put(Byte.TYPE, Byte.class);
primitiveWrapperMap.put(Character.TYPE, Character.class);
primitiveWrapperMap.put(Short.TYPE, Short.class);
primitiveWrapperMap.put(Integer.TYPE, Integer.class);
primitiveWrapperMap.put(Long.TYPE, Long.class);
primitiveWrapperMap.put(Double.TYPE, Double.class);
primitiveWrapperMap.put(Float.TYPE, Float.class);
primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}
public static Class primitiveToWrapper(Class cls) {
Class convertedClass = cls;
if (cls != null && cls.isPrimitive()) {
convertedClass = (Class) primitiveWrapperMap.get(cls);
}
return convertedClass;
}
public static boolean equalWithPrimitive(Class<?> from, Class<?> target) {
return primitiveToWrapper(from) == primitiveToWrapper(to);
}
This is also how the apache commons ClassUtils
library does it.
Upvotes: 2
Reputation: 41200
It might be little dirty but -
Get the name of the both classes convert those to lower case / upper case and equals them
Ex -
from.getName().toLowerCase().equals(target.getName().toLowerCase())
public static boolean equalWithPrimitive(Class<?> from, Class<?> target){
if(from == target){
return true;
}
return from.getName().toLowerCase().equals(target.getName().toLowerCase());
}
Upvotes: 1