2010-04-23 12 views
4

我想模擬用戶在java應用程序中的行爲,我想寫方法調用和參數到一個日誌文件,我將讀取並進行相同的調用。通過轉儲方法調用模擬客戶端活動記錄和模擬在java中的使用情況

我想這樣做使用反射(java.lang.reflect.Proxy)既將文件寫入日誌,然後讀取日誌並進行調用。是否有工具或方法來

1.Write到日誌文件中像這樣的方法的調用,例如: com.example.Order.doStuff(String的形式,INT B)

2。如果存在這樣的字段,則向日志文件寫出返回類型的內容: com.example.ReturnType [private fildname = contents]

3.閱讀此信息並使用反射進行上述調用?

謝謝。

回答

1

查找AOP(Aspect Oriented Programming) 這將允許您在方法周圍聲明攔截器,然後您可以簡單地使用攔截器寫入日誌文件。

下面是一個通過反射執行代碼的示例。

import java.lang.reflect.Method;

public class RunMthdRef { 
    public int add(int a, int b) { 
    return a+b; 
    } 

    public int sub(int a, int b) { 
    return a-b; 
    } 

    public int mul(int a, int b) { 
    return a*b; 
    } 

    public int div(int a, int b) { 
    return a/b; 
    } 

    public static void main(String[] args) { 
    try { 
     Integer[] input={new Integer(2),new Integer(6)}; 
     Class cl=Class.forName("RunMthdRef"); 
     Class[] par=new Class[2]; 
     par[0]=Integer.TYPE; 
     par[1]=Integer.TYPE; 
     Method mthd=cl.getMethod("add",par); 
     Integer output=(Integer)mthd.invoke(new RunMthdRef(),input); 
     System.out.println(output.intValue()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
}