反射获取对象的属性值
1 > bean 对象
package com.whbs.bean;
public class UserBean {
private Integer id ;
private int age ;
private String name ;
private String address ;
public UserBean(){
System. out .println( " 实例化 " );
}
public Integer getId() {
return id ;
}
public void setId(Integer id) {
this . id = id;
}
public int getAge() {
return age ;
}
public void setAge( int age) {
this . age = age;
}
public String getName() {
return name ;
}
public void setName(String name) {
this . name = name;
}
public String getAddress() {
return address ;
}
public void setAddress(String address) {
this . address = address;
}
}
2 > 反射测试
package com.whbs.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.whbs.bean.UserBean;
public class Test1 {
public static void main(String[] args) throws Exception {
/*
* 实列化类 方法 1
*/
//String classPath = "com.whbs.bean.UserBean";
//Class cla = Test1.class.getClassLoader().loadClass(classPath);
//Object ob = cla.newInstance();
/*
* 实列化类 方法 2
*/
UserBean bean = new UserBean();
bean.setId(100);
bean.setAddress( " 武汉 " );
// 得到类对象
Class userCla = (Class) bean.getClass();
/*
* 得到类中的所有属性集合
*/
Field[] fs = userCla.getDeclaredFields ();
for ( int i = 0 ; i < fs. length ; i++){
Field f = fs[i];
f.setAccessible( true ); // 设置些属性是可以访问的
Object val = f.get(bean); // 得到此属性的值
System. out .println( "name:" +f.getName()+ "/t value = " +val);
String type = f.getType().toString(); // 得到此属性的类型
if (type.endsWith( "String" )) {
System. out .println(f.getType()+ "/t 是 String" );
f.set(bean, "12" ) ; // 给属性设值
} else if (type.endsWith( "int" ) || type.endsWith( "Integer" )){
System. out .println(f.getType()+ "/t 是 int" );
f.set(bean,12) ; // 给属性设值
} else {
System. out .println(f.getType()+ "/t" );
}
}
/*
* 得到类中的方法
*/
Method[] methods = userCla.getMethods();
for ( int i = 0; i < methods. length ; i++){
Method method = methods[i];
if (method.getName().startsWith( "get" )){
System. out .print( "methodName:" +method.getName()+ "/t" );
System. out .println( "value:" +method.invoke(bean)); // 得到 get 方法的值
}
}
}
}
转至: http://blog.csdn.net/xiaopeng__/article/details/6950205
作 者:imsoft
Email:imsofter#163.com
出处:http://www.cnblogs.com/imsoft/
本文版权归作者和博客园共有,欢迎转载、交流,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。如果觉得本文对您有益,欢迎点赞、欢迎探讨。本博客来源于互联网的资源,若侵犯到您的权利,请联系博主予以删除。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
2015-09-20 MyEclipse junit测试问题initializationError