最后,我希望有一些与此类似的东西,我将用它来搜索正确的构造函数以进行反射。
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;
}
是否有更短更准确的方法来实现这一想法?
答案 0 :(得分:2)
最简单的方法是保留原始 - &gt;盒装类型的地图,并在进行检查之前将其用于转换:
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);
}
这也是apache commons ClassUtils
库的工作方式。
答案 1 :(得分:1)
可能有点脏,但是 -
Get the name of the both classes convert those to lower case / upper case and equals them
前 -
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());
}