這個問題我曾在論壇上發過,但沒有解答。放在這裡,給大家看看:
Think in partten of Java 中,關於Dynamic Proxies,有這麼一道習題:
Exercise: Use the Java dynamic proxy to create an object that acts as a front end for a simple configuration file. For example, in good_stuff.txt you can have entries like this:
a=1
b=2
c="Hello World"
A client programmer of this NeatPropertyBundle could then write:
NeatPropertyBundle p =
new NeatPropertyBundle("good_stuff");
System.out.println(p.a);
System.out.println(p.b);
System.out.println(p.c);
The contents of the configuration file can contain anything, with any variable names. The dynamic proxy will either map to the name or tell you it doesn’t exist somehow (probably by returning null). If you set a property and it doesn’t already exist, the dynamic proxy will create the new entry. The toString( ) method should display all the current entries.
我原本想這麼實現:
import java.lang.reflect.*;
import java.io.*;
class NeatPropertyBundle extends Proxy{
NeatPropertyBundle(final String textFileName){
super(new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args){
BufferedReader br=new BufferedReader(new FileReader(textFileName));
....../*這裡通過method.getName擷取要讀的欄位名,然後到設定檔裡讀取等等。*/
}
});
}
}
但我發現題目要求能對NeatPropertyBundle對象取任何成員變數值,而不是方法。變數名稱也是任意的,這應該如何??
---------------------------------------
論壇上的討論結果是,這是道錯題。看看各位有何意見。