Thursday, 17 March 2016

Java Reflection Part I

Java Reflection Example

Reference: http://tutorials.jenkov.com/java-reflection/index.html
Here is a quick Java Reflection example to show you what using reflection looks like:

Test.java

public class Test {

private String a;
private Integer b;
public Test(String a, Integer b) {
super();
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). 
Mainmethod2.java
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());
}
}

o/p:
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