Think in patten of Java中的一道习题

博主分享Think in partten of Java中关于Dynamic Proxies的习题,要求用Java动态代理为配置文件创建前端对象,可获取任意成员变量值。博主给出初步实现思路,但因题目要求难以实现,论坛讨论认为是错题,询问大家意见。

这个问题我曾在论坛上发过,但没有解答。放在这里,给大家看看:
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对象取任何成员变量值,而不是方法。变量名称也是任意的,这应该如何实现?
---------------------------------------
论坛上的讨论结果是,这是道错题。看看各位有何意见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值