본문 바로가기

개발/자바/jsp

object replacenull

모델객체들 if~ elseif~ null 체크할 필요없어서 편함

static void fillNullObjects(Object object) {
   
Field[] fields = object.getClass().getDeclaredFields();
   
for (Field field : fields) {
       
try {

            field.setAccessible(true);
           
if (field.get(object) != null) {
               
continue;
           
}
           
else if (field.getType().equals(Integer.class)) {
                field
.set(object, 0);
           
}
           
else if (field.getType().equals(String.class)) {
                field
.set(object, "");
           
}
           
else if (field.getType().equals(Boolean.class)){
                field
.set(object, false);
           
}
           
else if (field.getType().equals(Character.class)) {
                field
.set(object, '\u0000');
           
}
           
else if (field.getType().equals(Byte.class)) {
                field
.set(object, (byte) 0);
           
}
           
else if (field.getType().equals(Float.class)) {
                field
.set(object, 0.0f);
           
}
           
else if (field.getType().equals(Double.class)) {
                field
.set(object, 0.0d);
           
}
           
else if (field.getType().equals(Short.class)) {
                field
.set(object, (short) 0);
           
}
           
else if (field.getType().equals(Long.class)) {
                field
.set(object, 0L);
           
}
           
else if (field.getType().getDeclaredFields().length > 0){
               
for (Constructor<?> constructor : field.getClass().getConstructors()) {
                   
if (constructor.getParameterTypes().length == 0) {
                        field
.set(object, constructor.newInstance());
                        fillNullObjects
(field.get(object));
                   
}
               
}
           
}
      
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e
.printStackTrace();
       
}
   
}
}

 

'개발 > 자바/jsp' 카테고리의 다른 글

자바 리플렉션  (0) 2016.08.19
eclipse 실행오류 could not create java virtual machine  (0) 2013.10.18
트랜젝션 처리.  (0) 2012.04.20
ResultSet 연습  (0) 2012.03.29