读书人

反射有关问题(急)

发布时间: 2011-12-29 22:09:38 作者: rapoo

反射问题,在线等(急)
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(小连长)
写的不错 可以揭贴了

读书人网 >J2SE开发

热点推荐