使用内省方式操作JavaBean
内省,英文中称作introspector。主要对javaBean进行操作,JavaBean是一个特殊的Java类,该类中方法名符合特定的规则(其实就是getXXX,setXXX),我们一般是利用get,set方法来推断属性的名称,而不是直接根据属性来获得名称,因为属性都是私有的,而get,set方法都是共有的。推断规则:如果第二个字母为小写,则首字母小写,例如:
- getAge—>age
- setage—>age
由于自己根据方法名来推断属性名称非常麻烦,因此我们可以通过内省的方式来调用set,get方法,看看下面的例子:
@Test
public void test4() {
Person p1 = new Person();
Object value = "zhangsan";
String propertyName = "username";
try {
// 给属性设置值
setProperty(p1, value, propertyName);
// 获得属性值
System.out.println(getProperty(p1, propertyName));
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | IntrospectionException e) {
e.printStackTrace();
}
}
private Object getProperty(Object p1, String propertyName)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName,
p1.getClass());
Method methodGetProperty = pd1.getReadMethod();
return methodGetProperty.invoke(p1);
}
private void setProperty(Object p1, Object value, String propertyName)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName,
p1.getClass());
Method methodSetProperty = pd1.getWriteMethod();
methodSetProperty.invoke(p1, value);
}
Person.java
public class Person {
private String username;
private String password;
private int money;
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;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
使用JavaBean中提供的BeanInfo类来操作,这样略微麻烦,但也是一种实现方式:
private Object getProperty(Object p1, String propertyName)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
/*PropertyDescriptor pd1 = new PropertyDescriptor(propertyName,
p1.getClass());
Method methodGetProperty = pd1.getReadMethod();
return methodGetProperty.invoke(p1);*/
BeanInfo beanInfo = Introspector.getBeanInfo(p1.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds){
if(pd.getName().equals(propertyName)){
Method methodGetProperty = pd.getReadMethod();
return methodGetProperty.invoke(p1);
}
}
return null;
}
蓝天为路,阳光满屋。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?