Saturday, July 3, 2010

Java Reflection Examples


1. How to invoke or access a private method of an object or class in java

package basics;

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

class ReflectionExample {

/**
* Invokes a private method of an object using java Reflection.
*/
public void invokePrivateMethod() {

//Class instance
Class personClass = Person.class;

// Get methods
Method[] methods = personClass.getDeclaredMethods();

// Create the object to invoke the methods on
Person computer = new Person("Ivan");

if(methods.length>0)
{
try {

//This is very important to invoke a private method
// or to access a private variable
methods[0].setAccessible(true);

methods[0].invoke(computer, null);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return;
} catch (InvocationTargetException ex) {
ex.printStackTrace();
return;
} catch (IllegalAccessException ex) {
ex.printStackTrace();
return;
}
}
}

public static void main(String[] args) {
new ReflectionExample().invokePrivateMethod();
}
}

class Person {
private String name;

public Person(String name) {
this.name = name;
}

private void sayName() {
System.out.println("My name is : " + name);
}

}

The out put will be:
My name is : Ivan

2 comments:

  1. Thank you - just what i was looking for! Another good one that helped me very much:

    Java reflection example

    ReplyDelete