10/29/2009

Java Reflection 動態調用物件的方法

近來接觸Java Reflection,參考良葛格的例子做了些練習,下面是實作的code。

Student Class:
package com.iden.reflection;

public class Student {
 private String name;
    private int score; 

    public Student() { 
        name = "N/A"; 
    } 

    public Student(String name, int score) { 
        this.name = name; 
        this.score = score; 
    } 

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

    public String getName() { 
        return name; 
    } 

    public int getScore() { 
        return score; 
    } 

    public void showData() { 
        System.out.println("name: " + name); 
        System.out.println("score: " + score); 
    }
}


InvokeMethodDemo Class 調用Student object實作方法:
package com.iden.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeMethodDemo {
 
 private static String className;
 
    public static void main(String[] args) {
     //動態載入與呼叫方法
        try {
          
         if(args.length == 0)
          className = "com.iden.reflection.Student";
         else
          className = args[0];
          
            Class c = Class.forName(className);//呼叫Class
            Object targetObj = c.newInstance();//動態實作物件
            
            Class[] param1 = {String.class};
            Method setName = c.getMethod("setName", param1);//指定物件的方法            
            Object[] paramObjs1 = {"caterpillar"};
            setName.invoke(targetObj, paramObjs1);//將參數帶入方法
            
            
            Class[] param2 = {Integer.TYPE};
            Method setScore = c.getMethod("setScore", param2);            
            Object[] paramObjs2 = {new Integer(90)};
            setScore.invoke(targetObj, paramObjs2);
            
            
            Method showData = c.getMethod("showData", new Class[0]);
            showData.invoke(targetObj, new Object[0]);// call showData method to show name and score.
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
} 


感謝良葛格做了這麼棒的教學。
良葛格範例

沒有留言:

張貼留言