Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static <T> Object ConstructObjectWithDefaultValue( Object obj ) {
- try {
- //get all fields of class
- Field[] fields = obj.getClass().getDeclaredFields();
- Field[] fieldsSuperClass = obj.getClass().getSuperclass().getDeclaredFields();
- //set fields of base class
- if( fields!=null && fields.length > 0 ) {
- for( Field f : fields ) {
- setField(obj, f);
- }
- }
- //set fields of super class
- if( fieldsSuperClass!=null && fieldsSuperClass.length>0 ) {
- for(Field f : fieldsSuperClass ) {
- setField(obj, f);
- }
- }
- }catch (Exception e) {
- System.out.println( e.toString() );
- }
- return obj;
- }
- public static void setField( Object obj,Field f ) throws Error, IllegalArgumentException, IllegalAccessException{
- //override private access modifier
- f.setAccessible( true );
- //---PRIMITIVE_TYPES-------------------
- if( f.getType() == boolean.class ) {
- f.set(obj, false);
- }else if( f.getType() == boolean[].class ) {
- boolean[] boolArray = new boolean[0];
- f.set(obj, boolArray);
- }else if( f.getType() == int.class ) {
- f.set(obj, 0);
- }else if( f.getType() == short.class ) {
- f.set(obj, 0);
- }else if( f.getType() == int.class ) {
- f.set(obj, 0);
- }else if( f.getType() == long.class ) {
- f.set(obj, 0);
- }else if( f.getType() == float.class ) {
- f.set(obj, 0.0f);
- }else if( f.getType() == double.class ) {
- f.set(obj, 0.0d);
- }else if( f.getType() == char.class ) {
- f.set(obj, '0');
- }
- //---//PRIMITIVE_TYPES-----------------
- //---COMPLEX_JAVA_LANG_TYPES-----------
- else if( f.getType() == String.class ) {
- f.set(obj, "");
- }else if( f.getType() == Integer.class ) {
- f.set(obj, 0);
- }
- //---//COMPLEX_JAVA_LANG_TYPES---------
- //---COMPLEX_JAVA_UTIL_TYPES-----------
- else if( f.getType() == Calendar.class ) {
- Calendar c = Calendar.getInstance();
- c.setTime(new Date());
- f.set(obj, c);
- }else if( f.getType() == Date.class ) {
- f.set(obj, new Date());
- }
- //---//COMPLEX_JAVA_UTIL_TYPES---------
- //---CUSTOM_TYPES----------------------
- //---//CUSTOM_TYPES--------------------
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement