Wicia
Wicia

Reputation: 565

JAVA - Primitive type VS Object type

I have following variables:

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

Is it possible to compare it dynamically? It means that I want to get primitive tye of second variable and compare it with first.

Upvotes: 0

Views: 508

Answers (2)

Wicia
Wicia

Reputation: 565

@Sotirios Delimanolis, @WhiteboardDev thanks for leads. I have resolved this this way:

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;
}
}

Upvotes: 0

zapl
zapl

Reputation: 63955

There is no way to get int.class out of Integer.class or vice versa that is built into Java. You have to do the comparison manually.

  • Integer.class.isAssignableFrom(int.class) and the inverse thereof return false because it does not account for autoboxing (which is compiler generated code)
  • the only sign that you're dealing with a primitive type is Class#isPrimitive() which returns true for int.class (also void.class) but doesn't for int[].class, Integer.class for example.
  • Integer.TYPE and similar are aliases for int.class, ..

The smartest way to do this is to use a library or to write a few lines of code that cover all cases. There are only exactly 8 (boolean, byte, char, short, int, long, float, double) primitive types (+ void).

Upvotes: 1

Related Questions