繁体   English   中英

JAVA-基本类型VS对象类型

[英]JAVA - Primitive type VS Object type

我有以下变量:

Class a = int.class;
Class b = Integer.class;

是否可以动态比较? 这意味着我想获取第二个变量的原始类型并将其与第一个变量进行比较。

无法从Java内置的Integer.class获取int.class ,反之亦然。 您必须手动进行比较。

  • Integer.class.isAssignableFrom(int.class)及其反函数返回false因为它不考虑自动装箱(这是编译器生成的代码)
  • 你正在处理的一个基本类型的唯一标志是Class#isPrimitive()这对于返回true int.class (也void.class ),但不会对int[].classInteger.class例如。
  • Integer.TYPE和类似名称是int.class ,..的别名。

最聪明的方法是使用一个库或编写涵盖所有情况的几行代码。 仅存在8 byte基本类型( booleanbytecharshortintlongfloatdouble )(+ void )。

@Sotirios Delimanolis,@ 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;
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM