首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JAVA -原语类型与对象类型

问JAVA -原语类型与对象类型
EN

Stack Overflow用户
提问于 2015-12-23 19:38:11
回答 2查看 485关注 0票数 0

我有以下变量:

代码语言:javascript
复制
Class a = int.class;
Class b = Integer.class;

有可能动态比较吗?这意味着我想要得到第二个变量的原始tye,并将它与第一个比较。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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)。

票数 1
EN

Stack Overflow用户

发布于 2015-12-25 15:09:22

@Sotirios D分别奥利奥利,“WhiteboardDev”,谢谢你的领导。我已经这样解决了:

代码语言:javascript
复制
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;
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34442585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档