Java中的反射机制

发表于:2016-4-05 09:55

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:fthjane    来源:51Testing软件测试网采编

  Java使用反射机制使用get set 方法
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
*
*/
/**
* @ClassName: ReflectTest
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2013年11月26日 下午5:11:35
*
*/
public class ReflectTest {
public static void main() throws Exception{
ReflectTest bo = new ReflectTest();
Field[] fields = bo.getClass().getDeclaredFields();
// 写数据
for(Field ff : fields) {
String name = ff.getName();    //获取属性的名字
String type = ff.getGenericType().toString();    //获取属性的类型
ff.setAccessible(true);
PropertyDescriptor pd = new PropertyDescriptor(ff.getName(), bo.getClass());
Method rM = pd.getReadMethod();//获得读方法
Object num = (Object) rM.invoke(bo);
if(num == null) {
Method wM = pd.getWriteMethod();//获得写方法
if(type.equals("class java.lang.Integer")){
}
if(type.equals("class java.lang.Short")){
}
if(type.equals("class java.lang.Double")){
}
if(type.equals("class java.lang.Boolean")){
}
if(type.equals("class java.util.Date")){
}
wM.invoke(bo, "1");//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
}
}
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号