tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Tools and Libs > Commons Bean Utils > Invoke Method

Invoke Method 

Apache Commons BeanUtils is a java library useful for accessing bean properties and methods. It provides introspection capabilities to view and manipulate the properties and operations provided by the given class. This requires the libraries commons-beanutils-1.8.3.jar, commons-beanutils-bean-collections-1.8.3.jar, commons-beanutils-core-1.8.3.jar, commons-collections-3.2.1.jar, commons-logging.jar to be in classpath. The following example shows using MethodUtils.invokeMethod() API. It invokes the named method with given arguments.

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

public class Student {

  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/commons_beanutils/InvokeMethodTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.commons_beanutils;

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.MethodUtils;
import com.bethecoder.tutorials.commons_beanutils.common.Student;

public class InvokeMethodTest {

  /**
   @param args
   @throws InvocationTargetException 
   @throws IllegalAccessException 
   @throws NoSuchMethodException 
   */
  public static void main(String[] argsthrows NoSuchMethodException, 
    IllegalAccessException, InvocationTargetException {
    
    Student std = new Student("Sriram"2"Chess");
    String name = (StringMethodUtils.invokeMethod(std, "getName"null);
    System.out.println(name);
    
    Integer age = (IntegerMethodUtils.invokeMethod(std, "getAge"null);
    System.out.println(age);
    
    Boolean contains = (BooleanMethodUtils.invokeMethod(name, "contains""Sri");
    System.out.println(contains);
    
    name = (StringMethodUtils.invokeMethod(name, "concat"new Object [] { " Kasireddi" });
    System.out.println(name);
    
  }

}
   

It gives the following output,
Sriram
2
true
Sriram Kasireddi


                    Print

   



Books Recommendation

 
 
bl  br