March 09, 2012

Reflection example in java


Example for reflection in java

Reflection in java makes it possible to inspect and call classes, methods, attributes etc dynamically at run time. Reflection is not possible in other programming languages such as c++.

Here i wrote a simple java program to know how reflection works.

StudentModel.java


/**
* JavaBelazy Java source code download
*/

/**
* @author +belazy
*
*/
public class StudentModel {

private String name = "javasourcecode";

private int id = 622;

private boolean isPassed = false;

//private double totalMark = 788;



public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public boolean isPassed() {
return isPassed;
}

public void setPassed(boolean isPassed) {
this.isPassed = isPassed;
}





}





Main class

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* Reflection example in java source code available
*/

/**
* @author +Belazy L
*
*/
public class Main {

public static void main(String[] args) {

try {
Class n = Class.forName("StudentModel");
StudentModel st = new StudentModel();

System.out.println(" ------------------ All methods ---------------");
Method []m = n.getMethods();
//Method a= n.getMethod("get");
for(int i=1;i< field.length; i++)
{
System.out.println(field[i].getName());
}


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


Thanking you....

1 comment:

  1. Simple example for reflection class...

    ReplyDelete

Your feedback may help others !!!

Facebook comments