假设一个javaBean类,有两个属性,userName和password,现在如果想通过属性名来找其对应的属性值的话,我们就要用到java反射了,我这里的方法是根据attribute name组装method方法,然后利用method的invoke方法,就可以获取到attribute value了!下面直接上代码
dto类:
public class Dto {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
处理方法:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class t {
public static void main(String[] args){
Dto d = new Dto();
d.setUserName("LRR");
d.setPassword("123");
// 已知attribute name 组装 getter语句
String getter = "get" + "UserName";// getUserName
try {
// 通过method的反射方法获取其属性值
Method method = d.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(d, new Object[]{});
System.out.print(value);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果:LRR