priojewo
priojewo

Reputation: 947

Check different objects for null value

This could be quite a stupid question, but I am not sure how to solve this.

int num;
String str;
float flt;

I define three variables, one int, one String and one float. Than I do the following:

Object a = num;
Object b = str;
Object c = flt;

How can I check the a, b or c object for the default value? I know that it is null for String, 0 for int, and 0.0 for float, but is there a way to do some sort of:

if(a==nullValue(a) && b==nullValue(b) && c==nullValue(c))

so that it is equal to:

if(a==0 && b==null && c==0.0)

I just get the three a, b, c objects passed and so I don't know which type they are.

Upvotes: 0

Views: 114

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

Add this to the class of your choice.

private static final List<? extends Object> DEFAULTS = 
    Arrays.asList( null, (byte) 0, (short) 0, 0, 0L, 0F, 0D, '\u0000', false );

private static boolean isDefault(Object o) {
    return DEFAULTS.contains(o);
}

Upvotes: 1

kiruwka
kiruwka

Reputation: 9450

Java is a strongly typed language and you are trying to defeat and not utilize one of its core strengths.

Technically speaking, you can achieve what you want, generally you will have to test your Object obj against all possible primitive types + null (since you don't know what this Object really is ):

     static boolean isDefaultValue(Object obj) {

        if (obj == null // non-primitive
                || obj.equals((byte) 0) // default for byte
                || obj.equals((short) 0) // short
                || obj.equals((int) 0) // int
                || obj.equals(0L) // long
                || obj.equals(0.0f) // float 
                || obj.equals(0.0d) // double
                || obj.equals('\u0000') // char 
                || obj.equals(false)) { // boolean

            return true;
        }
        return false;
    }

However, instead of doing this, I really encourage you to revise your design and ask yourself why you completely erase data types by casting everything to Object. This could lead to unreadable and highly dangerous code.

Post your reason, and we might help you find better solution.

Upvotes: 2

MMendes
MMendes

Reputation: 84

For type checking you should use instanceof like this

Object obj = null;
        int num = 0;
        String str = null;
        float flt = 0f;

        obj = num;
//      obj = str;
//      obj = flt;
        if(obj instanceof Integer){
            //THEN IT SHOULD BE 0
        }
        else if(obj instanceof String){
            //THEN IT SHOULD BE NULL
        }
        else if(obj instanceof Float){
            //THEN IT SHOULD BE NULL
        }
        else{
            //IT IS NULL BECAUSE Object obj = null;
        }

It works for any type.

Upvotes: -1

Related Questions