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 set declared bean property value by name

How to set declared 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 set declared bean property value by property name using BeanUtil.setDeclaredProperty() API. If a setter method exists for a given property then it uses the same otherwise accesses the field directly.

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

public class Student2 {

  private String name;
  private int age;
  private String hobby;

  public void setName(String name) {
    System.out.println("In setName method with name : " + name);
    this.name = name;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

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

import jodd.bean.BeanUtil;

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

public class SetDeclaredPropertyTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    Student2 std = new Student2();
    
    //Tries to invoke the setter method for given property
    //If not found sets the field directly. 
    BeanUtil.setDeclaredProperty(std, "name""Sriram");
    BeanUtil.setDeclaredProperty(std, "age"2);
    BeanUtil.setDeclaredProperty(std, "hobby""Chess");
    
    System.out.println(std);
  }

}
   

It gives the following output,
In setName method with name : Sriram
Student[name = Sriram, age = 2, hobby = Chess]



 
  


  
bl  br