Thursday, 17 March 2016

Java Reflection Part I

Java Reflection Example

Here is a quick Java Reflection example to show you what using reflection looks like:

public class Test {

private String a;
private Integer b;
public Test(String a, Integer b) {
this.a = a;
this.b = b;
public String getA() {
return a;
public void setA(String a) {
this.a = a;
public Integer getB() {
return b;
public void setB(Integer b) {
this.b = b;

     This example obtains the Class object from the class called Test. Using the class object the example gets a list of the
    methods in that class, iterates the methods and print out their names.

Exactly how all this works is explained in further detail throughout the rest of this tutorial (in other texts).
public class Mainmethod2 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Method[] methods = Test.class.getMethods();

for(Method method : methods){
   System.out.println("method = " + method.getName());

method = getA
method = setA
method = getB
method = setB
method = wait
method = wait
method = wait
method = equals
method = toString
method = hashCode
method = getClass
method = notify
method = notifyAll

No comments:

Post a Comment