views:

278

answers:

5

I have a java primitive type at hand:

Class c = int.class; // or long.class, or boolean.class

I'd like to get a 'default value' for this class - specifically the value is assigned to fields of this type if they are not initialized. E.g., '0' for a number, 'false' for a boolean.

Is there a generic way to do this? I tried

c.newInstance()

But I'm getting an InstantiationException, and not a default instance.

+1  A: 

There isn't an elegant way to do this. In fact, it is not even possible to declare the signature of a method that will return the primitive values per se.

The closest you can come is something like this:

public Object defaultValue(Class cls) {
    if (class == Boolean.TYPE) {
        return Boolean.FALSE;
    } else if (class == Byte.TYPE) {
        return Byte.valueOf(0);
    } else if (class == Short.TYPE) {
        ...
    } else {
        return null;
    }
}
Stephen C
The signature is simple: Object getDefaultValue(Class type)
ripper234
That won't work because of the return value. int, long etc aren't `java.lang.Object`s, unless you're OK with returning wrapper classes (`java.lang.Integer`, `java.lang.Long` etc).
Jack Leow
@ripper234 - but that returns wrapper instances not instances of the primitive types.
Stephen C
In fact, you can declare the signature of the method above like this: `public static <T> T defaultValue(Class<T> cls)`
newacct
@newacct - yes you can, though it won't necessarily help for the use case that I imagine the OP has in mind.
Stephen C
I'm ok with returning wrapper classes.
ripper234
A: 

You can do this with reflection, but it's easiest and clearest to write it out, e.g.

Object defaultValue(Class cls)
{
  Map defaults = new HashMap();
  defaults.put(Integer.TYPE, Integer.valueOf(0));  
  defaults.put(Double.TYPE, Double.valueOf(0));  
  defaults.put(Boolean.TYPE, Boolean.FALSE);  
  //... etc
  return defaults.get(cls);
}

Of course, you will probably want to move the map initialization out to a constructor or similar for once-only initialization.

Reasonably concise - it is elegant?

mdma
+1  A: 

This is what I'm thinking (fails the elegance test though):

public class PrimitiveDefaults {
    // These gets initialized to their default values
    private static boolean DEFAULT_BOOLEAN;
    private static byte DEFAULT_BYTE;
    private static short DEFAULT_SHORT;
    private static int DEFAULT_INT;
    private static long DEFAULT_LONG;
    private static float DEFAULT_FLOAT;
    private static double DEFAULT_DOUBLE;

    public static Object getDefaultValue(Class clazz) {
        if (clazz.equals(boolean.class)) {
            return DEFAULT_BOOLEAN;
        } else if (clazz.equals(byte.class)) {
            return DEFAULT_BYTE;
        } else if (clazz.equals(short.class)) {
            return DEFAULT_SHORT;
        } else if (clazz.equals(int.class)) {
            return DEFAULT_INT;
        } else if (clazz.equals(long.class)) {
            return DEFAULT_LONG;
        } else if (clazz.equals(float.class)) {
            return DEFAULT_FLOAT;
        } else if (clazz.equals(double.class)) {
            return DEFAULT_DOUBLE;
        } else {
            throw new IllegalArgumentException(
                "Class type " + clazz + " not supported");
        }
    }
}
Jack Leow
A: 

Class variables of primitives do not need to be initialized or set with a default value. However variables declare in other scope must be initialized or you'll get compilation errors.

public class PrimitiveStuff {
private int aInt;
private long aLong;
private boolean aBoolean;

public PrimitiveStuff() {
    System.out.println("aInt : "  + aInt); //prints 0
    System.out.println("aLong: "+ aLong);//prints 0
    System.out.println("aBoolean: " + aBoolean);//prints false
}


public void doStuff(){
    int outherInt;
    System.out.println(outherInt); //will not compile
}

public static void main(String[] args) {
    new PrimitiveStuff();
}

}

Kennet
+8  A: 

The Guava Libraries already contains that:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Defaults.html

Willi