有三个类
- 一个是User类,是一个JavaBean类;
- 一个是BeanUtil,提供方法来通过属性名获取属性值
- 一个是MethodDemo类,用于测试。
测试时通过User类的属性名来获取其属性值
User.java
package com.imooc.reflect;
//标准的JavaBean类有私有属性都对应有get/set方法,有无参数的构造方法
public class User {
private String username;
private String userpass;
private int age;
public User(){}
public User(String username, String userpass, int age) {
super();
this.username = username;
this.userpass = userpass;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
BeanUtil.java
package com.imooc.reflect;
import java.lang.reflect.Method;
public class BeanUtil {
/**
* 根据标准javaBean对象的属性名获取其属性值
*
* @param obj
* @param propertyName
* @return
*/
public static Object getValueByPropertyName(Object obj, String propertyName) {
// 1.根据属性名称就可以获取其get方法
String getMethodName = "get"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
//2.获取方法对象
Class c = obj.getClass();
try {
//get方法都是public的且无参数
Method m= c.getMethod(getMethodName);
//3 通过方法的反射操作方法
Object value = m.invoke(obj);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
MethodDemo.java
package com.imooc.reflect;
public class MethodDemo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
User u1 = new User("zhangsan", "123456", 30);
System.out.println(BeanUtil.getValueByPropertyName(u1, "username"));
System.out.println(BeanUtil.getValueByPropertyName(u1, "userpass"));
}
}
先通过构造函数实例化一个User对象u1,username是“zhangsan”, 密码是“123456”,年龄30岁。
调用BeanUtil类中的==getValueByPropertyName(Object, String))==来获取属性值。
获取过程:
BeanUtil.getValueByPropertyName(u1, "username")
将u1对象,"username"作为参数传入时,先对username做处理
String getMethodName = "get"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
在字符串前加上 “get”,然后将字符串的第一个字母变为大写,然后将剩下的字符串加上,传入的 “username” 变为 getUsername
,这正是User类中的方法名getUsername,然后获取u1对象的类的类类型,通过方法反射,获取属性值,再将之返回。
// 获取 u1 类的类类型
Class c = u1.getClass();
// 获取 getUsername 方法
Method m = c.getMethod(getMethodName);
// 执行getUsername方法,并返回属性值给 returnVal
Object returnVal = m.invoke(u1);
return returnVal;