我有以下变量:
Class a = int.class;
Class b = Integer.class;有可能动态比较吗?这意味着我想要得到第二个变量的原始tye,并将它与第一个比较。
发布于 2015-12-23 20:31:13
没有办法将int.class从Integer.class中提取出来,反之亦然,这是构建在Java中的。你必须手动进行比较。
Integer.class.isAssignableFrom(int.class)及其逆序返回false,因为它不考虑自动装箱(这是编译器生成的代码)。Class#isPrimitive(),它返回int.class (也是void.class)的true,但对于int[].class (例如Integer.class )则不返回。Integer.TYPE和类似的是int.class的别名。最聪明的方法是使用一个库或编写几行涵盖所有情况的代码。只有8种原语类型(boolean、byte、char、short、int、long、float、double) (+ void)。
发布于 2015-12-25 15:09:22
@Sotirios D分别奥利奥利,“WhiteboardDev”,谢谢你的领导。我已经这样解决了:
public class Types {
private Map<Class, Class> mapWrapper_Primitive;
public Types(){
this.mapWrapper_Primitive = new HashMap<>();
this.mapWrapper_Primitive.put(Boolean.class, boolean.class);
this.mapWrapper_Primitive.put(Byte.class, byte.class);
this.mapWrapper_Primitive.put(Character.class, char.class);
this.mapWrapper_Primitive.put(Double.class, double.class);
this.mapWrapper_Primitive.put(Float.class, float.class);
this.mapWrapper_Primitive.put(Integer.class, int.class);
this.mapWrapper_Primitive.put(Long.class, long.class);
this.mapWrapper_Primitive.put(Short.class, short.class);
this.mapWrapper_Primitive.put(Void.class, void.class);
}
public boolean areDerivedTypes(Class type1, Class type2){
// Checking object types
if(!type1.isPrimitive() && !type2.isPrimitive()){
return type1.equals(type2);
}
// Checking primitive types
Class typeA = toPrimitiveType(type1);
Class typeB = toPrimitiveType(type2);
return typeA.equals(typeB);
}
public Class toPrimitiveType(Class type){
Class value = this.mapWrapper_Primitive.get(type);
if(value != null){
return value;
}
return type;
}
}https://stackoverflow.com/questions/34442585
复制相似问题