Làm thế nào để gọi và thực thi method bằng cách sử dụng reflection.

Đầu tiên để thực hiện ví dụ này các bạn tạo cho mình 1 class Money

[code language=”java”]

public class Money {
public double vnd;
public double dollar;

public Money(double vnd, double dollar) {
     super();
     this.vnd = vnd;
     this.dollar = dollar;
}
public double getVnd() {
     return vnd;
}
public void setVnd(double vnd) {
     this.vnd = vnd;
}
public double getDollar() {
     return dollar;
}
public void setDollar(double dollar) {
     this.dollar = dollar;
}
//Để ý phương thức này lát nữa sẽ dùng nó để truy cập
//Quy đổi Dollar sang VND
public double exchangeDollarToVND(double dollar){
     return dollar * 22783.50;
}
}
[/code]

Ví dụ một method cho bởi tên, các tham số định trước ghi ra kết quả thực thi method này

[code language=”java”] import java.lang.reflect.Method;

public class ExecuteMethod {
public static void main(String[] args) throws Exception {
     //Lấy ra đối tượng của class mô tả money
     Class<Money> clazz = Money.class;
     Money money = new Money(0.0, 0.0);

/*Lấy ra đối tượng của Method mô tả phương thức ‘exchangeDollarToVND’
của class Money*/
     Method method = clazz.getMethod("exchangeDollarToVND",double.class);

     //Gọi phương thức bằng reflector
/*Ở đây các bạn cứ hình dung nó giống như gọi money.exchangeDollarToVND(3);*/
     Object obj = method.invoke(money, 3);
     System.out.println("Dollar to VND = "+obj);
  }
}
[/code]

Kết quả trả về:

Screenshot (66)

-N-13