본문 바로가기

Java

자바빈(javaBean) 의 값을 보다 쉽게 확인하는 util

1. 자바빈 생성

public class BoardBean {
  private String name;
  private String title;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getTitle() {
    return title;
  }
  public void setTitle(String title) {
    this.title = title;
  }
}



2. 확인

public class BeanTest {
 
 
  public static void main(String[] args) {
    BoardBean board = new BoardBean();
    board.setName("jsp");
    board.setTitle("javaproject");
     
    try {
      System.out.println( BeanUtils.getBeanGetValue(board));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}



3. 출력
name = jsp
title = javaproject
class = class BoardBean


@.JavaBean Util 소스

import java.lang.reflect.Method;

public class BeanUtils {

public static String getBeanGetValue(Object obj) throws Exception {

     StringBuffer temp = new StringBuffer();

     Class cls = obj.getClass();

     Method[] method = cls.getMethods();
     String methodName = "";

     for(int i = 0; i < method.length; i++) {
          methodName = method[i].getName();
          if(methodName.indexOf("get")==0) {

           String fName = methodName.substring(methodName.indexOf("get") 
                                                     + 3).toLowerCase();

           String fValue = "";
           Object fValueObj = method[i].invoke(obj,null);

           if(fValueObj == null) {
              fValue = "null";
           } else {
              fValue = fValueObj.toString();
           }

             temp.append(fName + " = " + fValue + "\n");
        }
     } 
  
     return temp.toString();
     }
}