tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > Jodd > Beans > How to get bean property value by name

How to get bean property value by name 

Jodd is an open-source java library with lot of reusable components and feature rich utilities. This requires the library jodd-3.3.2.jar to be in classpath. The following example shows how to get bean property value given the property name using BeanUtil.getProperty() API. It throws jodd.bean.BeanException if the specified property is not found.

File Name  :  
com/bethecoder/tutorials/jodd/common/Student.java 
   
package com.bethecoder.tutorials.jodd.common;

public class Student implements java.io.Serializable {

  private static final long serialVersionUID = -5962595557796049374L;
  private String name;
  private int age;
  private String hobby;

  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/jodd/beans/GetPropertyTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.jodd.beans;

import jodd.bean.BeanUtil;

import com.bethecoder.tutorials.jodd.common.Student;

public class GetPropertyTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    Student std = new Student("Sriram"2"Chess");
    
    String name = (StringBeanUtil.getProperty(std, "name");
    System.out.println(name);
    
    Integer age = (IntegerBeanUtil.getProperty(std, "age");
    System.out.println(age);
    
    try {
      String unknown = (StringBeanUtil.getProperty(std, "unknown");
      System.out.println(unknown);
    catch (jodd.bean.BeanException e) {
      System.out.println(e);
    }
  }

}
   

It gives the following output,
Sriram
2
jodd.bean.BeanException: Simple property not found: 
	unknown Invalid property: 'Student#unknown' (actual:'Student#unknown', forced=false)



 
  


  
bl  br