วันพุธที่ 5 กุมภาพันธ์ พ.ศ. 2557

Java Reflect

ปกติแล้วเราจะเรียกใช้งาน method ใน class โดยการ สร้าง object class นั้น ๆ แล้วเรียกใช้งาน method ใน class

เช่น 

A obj = new A();
obj.method();

แต่ยังมีอีกวิธีนึง คือการเรียกใช้งาน แบบ reflect ตัวอย่างเช่น

แบบที่ 1 (ธรรมดา)

1. Class Service มี method hello() ไว้ให้เรียกใช้งาน

package demo.reflect;

public class Services {

    public String hello() throws InterruptedException {
        return "Hi method hello()";

    }
}


2. Class Test เป็น class ที่เรียกใช้งาน method hello ของ class Service โดยวิธีการ reflect

package demo.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test {

    public static void main(String[] args) {
        try {
            Services clazz = new Services();
            Method method = clazz.getClass().getMethod("hello", new Class[]{});
            Object ret = method.invoke(clazz, new Object[]{});
            System.out.println("result : " + ret);
        } catch (Exception ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

แบบที่ 2 (ส่ง Parameter ไปด้วย)


1. Class Service มี method hello() ไว้ให้เรียกใช้งาน

package demo.reflect;

public class Services {

    public String hello(String name) throws InterruptedException {
       return "Hi " + name;
    }
}


2. Class Test เป็น class ที่เรียกใช้งาน method hello ของ class Service โดยวิธีการ reflect

package demo.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test {

    public static void main(String[] args) {
        try {
            Services clazz = new Services();
            Method method = clazz.getClass().getMethod("hello", new Class[]{String.class});
            Object ret = method.invoke(clazz, new Object[]{"aekasit"});
            System.out.println("result : " + ret);
        } catch (Exception ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น