This short article shows how Reflection works using Java.
I am extract the source from http://examples.javacodegeeks.com/core-java/reflection/java-reflection-example/.
First you need to import the following namespace.
import java.lang.reflect.*;
You have a class with a method in RentCar
public class RentCar {
private int rate;
public void computeRentalCost(int numDays) {
price = numDays * rate;
System.out
.println(“The cost of your rental car is “ + price + ” euros”);
}
}
To do Reflection (code fragment below).
Class rental = RentCar.class;
// get method with specific name and parameters
Method oneMethod = rental.getMethod(“computeRentalCost”,
new Class[] { Integer.TYPE });
System.out.println(“Method is: “ + oneMethod);
// call computeRentalCost method with parameter int
oneMethod.invoke(rent, 4);
// get all the parameters of computeRentalCost
Class[] parameterTypes = oneMethod.getParameterTypes();
System.out.println(“Parameter types of computeRentalCost() are: “
+ Arrays.toString(parameterTypes));
The re-upload the project to http://skydrive.live.com. The sample file name is JavaReflectionExample2.zip My MSN ID is chanmmn@hotmail.com.