tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > Commons Lang3 > Classes > Get Method

Get Method 

Apache Commons Lang 3.0 is a java library with lot of utilities and reusable components. This requires the library commons-lang3-3.0.1.jar to be in classpath. The following example shows using ClassUtils.getPublicMethod() API. It returns the public Method like Class.getMethod, however it ensures that the returned Method is from a public class or interface and not from an anonymous inner class.

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

public class Student extends Person {

  private static String DEFAULT_NAME = "Unknown";
  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_lang/tests/classes/GetMethodTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.commons_lang.tests.classes;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang3.ClassUtils;

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

public class GetMethodTest {

  /**
   @param args
   @throws NoSuchMethodException 
   @throws SecurityException 
   @throws InvocationTargetException 
   @throws IllegalAccessException 
   @throws IllegalArgumentException 
   */
  public static void main(String[] argsthrows SecurityException, 
          NoSuchMethodException, IllegalArgumentException, 
          IllegalAccessException, InvocationTargetException {
  
    Student std = new Student("Sriram"2"Chess");
    Method meth = ClassUtils.getPublicMethod(std.getClass()
        "getName"new Class<?> [] {});
    String name = (Stringmeth.invoke(std, new Object [] {});
    System.out.println("Name : " + name);
  }
}
   

It gives the following output,
Name : Sriram



 
  


  
bl  br