0% found this document useful (0 votes)
3 views

demo2

Uploaded by

caotribo123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

demo2

Uploaded by

caotribo123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

HashMap;
import java.util.Map;

public class DefaultValueRetriever {

// Map to hold the default values for wrapper classes


private static final Map<Class<?>, Object> defaultValueMap = new HashMap<>();

static {
// Populating the default value map for wrapper classes
defaultValueMap.put(Integer.class, 0);
defaultValueMap.put(Boolean.class, false);
defaultValueMap.put(Character.class, '\u0000');
defaultValueMap.put(Byte.class, (byte) 0);
defaultValueMap.put(Short.class, (short) 0);
defaultValueMap.put(Long.class, 0L);
defaultValueMap.put(Float.class, 0.0f);
defaultValueMap.put(Double.class, 0.0);
defaultValueMap.put(String.class, null); // Reference types default to null
}

public static Object getDefaultValue(Object obj) {


if (obj == null) {
return null; // Return null for null input
}

// Check the map for the corresponding default value for the class
Class<?> clazz = obj.getClass();

// Handle primitive types using their wrapper classes


if (clazz.isPrimitive()) {
return getPrimitiveDefaultValue(clazz);
}

// Return the default value from the map if found


return defaultValueMap.getOrDefault(clazz, null);
}

private static Object getPrimitiveDefaultValue(Class<?> clazz) {


if (clazz == int.class) {
return 0;
} else if (clazz == boolean.class) {
return false;
} else if (clazz == char.class) {
return '\u0000';
} else if (clazz == byte.class) {
return (byte) 0;
} else if (clazz == short.class) {
return (short) 0;
} else if (clazz == long.class) {
return 0L;
} else if (clazz == float.class) {
return 0.0f;
} else if (clazz == double.class) {
return 0.0;
}
return null; // Return null if it's not a recognized primitive
}
public static void main(String[] args) {
// Test cases for different types
System.out.println("Default value for Integer: " + getDefaultValue(1));

}
}

You might also like