日期:2014-05-20  浏览次数:20719 次

反射问题,在线等(急)
public   class   book{

        private   String   name;
        private   String   author;

        public   String   getName(){
                return   this.name;
        }

        public   void   setName(String   name){
                this.name   =   name;
        }
                            ...(get、set方法)
}

现在我只知道book有一属性name,怎么通过反射调用它的get和set方法呢?请给出代码,谢谢!

------解决方案--------------------
try {
Book book = new Book();
Method get = book.getClass().getMethod( "getBook ");
Object obj = get.invoke(book);
System.err.println(obj);

} catch (Exception e) {
e.printStackTrace();
}
------解决方案--------------------
为什么不用getConstructor(),newInstance()等方法构造一个Book对象呢,然后在调用该方法
------解决方案--------------------
刚写的,你看看是不是你要的~
book bk = new book();
Class c = bk.getClass();
Method[] met = c.getMethods();
//设置bean中的值
for (int i = 0; i < met.length; i++) {
if (met[i].getName().startsWith( "set ")) {
String bookname = met[i].getName().substring(3).toLowerCase();
if (bookname.equals( "name ")) {
try {
met[i].invoke(bk, new Object[] { "noki "});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
//获取bean中的值
for (int i = 0; i < met.length; i++) {
if (met[i].getName().startsWith( "get ")) {
String bookname = met[i].getName().substring(3).toLowerCase();
if (bookname.equals( "name ")) {
try {
String print = met[i].invoke(bk).toString();
System.out.println(print);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
------解决方案--------------------
mark
------解决方案--------------------
huacius(小连长)
写的不错 可以揭贴了