java中使用反射来遍历实体类和其父类的所有属性和值

很多时候我们在项目中并不会知道传过来的一个对象的真实类型,自然也无法使用这个类型的get方法获取这个传过来的对象的属性和属性对应的值,当时我们使用反射则可以方便的获取传递过来的未知类对象的所有的属性(包含所有父类)值。

下面的第一个代码处理的是仅仅获取本类中的所有的属性和属性值的方法。

public static void testReflect(Object model) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        Field[] field = model.getClass().getDeclaredFields();        //获取实体类的所有属性,返回Field数组  
        for(int j=0 ; j<field.length ; j++){     //遍历所有属性
                String name = field[j].getName();    //获取属性的名字
                
                System.out.println("attribute name:"+name);     
                name = name.substring(0,1).toUpperCase()+name.substring(1); //将属性的首字符大写,方便构造get,set方法
                String type = field[j].getGenericType().toString();    //获取属性的类型
                if(type.equals("class java.lang.String")){   //如果type是类类型,则前面包含"class ",后面跟类名
                    Method m = model.getClass().getMethod("get"+name);
                    String value = (String) m.invoke(model);    //调用getter方法获取属性值
                    if(value != null){
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.lang.Integer")){     
                    Method m = model.getClass().getMethod("get"+name);
                    Integer value = (Integer) m.invoke(model);
                    if(value != null){
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.lang.Short")){     
                    Method m = model.getClass().getMethod("get"+name);
                    Short value = (Short) m.invoke(model);
                    if(value != null){
                        System.out.println("attribute value:"+value);                    }
                }       
                if(type.equals("class java.lang.Double")){     
                    Method m = model.getClass().getMethod("get"+name);
                    Double value = (Double) m.invoke(model);
                    if(value != null){                    
                        System.out.println("attribute value:"+value);  
                    }
                }                  
                if(type.equals("class java.lang.Boolean")){
                    Method m = model.getClass().getMethod("get"+name);    
                    Boolean value = (Boolean) m.invoke(model);
                    if(value != null){                      
                        System.out.println("attribute value:"+value);
                    }
                }
                if(type.equals("class java.util.Date")){
                    Method m = model.getClass().getMethod("get"+name);                    
                    Date value = (Date) m.invoke(model);
                    if(value != null){
                        System.out.println("attribute value:"+value.toLocaleString());
                    }
                }  
                              
            }
    }

如果想要获取传递过来的对象的所有属性和值甚至其所有父类的所有的属性和值的话,需要将上述代码改为下面的代码处理:

@SuppressWarnings("rawtypes")
	public static void getObjProVal(Object o, Class _class)
			throws JSONException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException,
			NoSuchFieldException, SecurityException {
		while (_class != null) {
			Method[] methods = _class.getDeclaredMethods();// 获得类的方法集合
			// 遍历方法集合
			for (int i = 0; i < methods.length; i++) {
				// 获取所有getXX()的返回值
				if (methods[i].getName().equals("getClass")) {
					continue;
				}
				if (methods[i].getName().startsWith("get")) {// 方法返回方法名
					methods[i].setAccessible(true);// 允许private被访问(以避免private
					String methodName = methods[i].getName();
					String proName = methodName.substring(3, 4).toLowerCase()
							+ methodName.substring(4);

					String type = _class.getDeclaredField(proName)
							.getGenericType().toString();
					int index = type.lastIndexOf(".");
					if (index > 0 && type.substring(index + 1).equals("Date")) {
						Date value = (Date) methods[i].invoke(o, null);
						if (value != null) {
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd");
							String str = sdf.format(value);
							System.out.println("属性"+proName+"的类型为:"+type+",值为:"+str);
						}
					} else {
						Object object = methods[i].invoke(o, null);
						System.out.println("属性"+proName+"的类型为:"+type+",值为:"+object);
					}

				}
			}
			_class = _class.getSuperclass();
		}
	}

如果各位朋友们想进一步把获取到的对象的类名和属性名、属性的类型以及属性对应的值封装起来并且返回给调用者,那么,可以使用以下方法,注意下面的方法需要导入org.json.jar,调用这个getObjVal()方法就会返回一个jsonObject对象,这个对象封装了传递过来的未知对象的所有的非空属性对应的值,如果想要把空的值对应的属性也添加进来,只需将getObjProVal方法中的判断值为空的代码去掉即可。

public static JSONObject getObjVal(Object object) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("className", object.getClass().getSimpleName());
			jsonObject
					.put("condition", getObjProVal(object, object.getClass()));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(jsonObject);
		return jsonObject;
	}

	@SuppressWarnings("rawtypes")
	public static JSONArray getObjProVal(Object o, Class _class)
			throws JSONException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException,
			NoSuchFieldException, SecurityException {
		JSONArray jsonArray = new JSONArray();
		while (_class != null) {
			Method[] methods = _class.getDeclaredMethods();// 获得类的方法集合
			// 遍历方法集合
			for (int i = 0; i < methods.length; i++) {
				// 获取所有getXX()的返回值
				if (methods[i].getName().equals("getClass")) {
					continue;
				}
				if (methods[i].getName().startsWith("get")) {// 方法返回方法名
					JSONObject jsonObject = new JSONObject();
					methods[i].setAccessible(true);// 允许private被访问(以避免private
													// getXX())
					String methodName = methods[i].getName();
					String proName = methodName.substring(3, 4).toLowerCase()
							+ methodName.substring(4);
					jsonObject.put("pro", proName);

					String type = _class.getDeclaredField(proName)
							.getGenericType().toString();
					int index = type.lastIndexOf(".");
					jsonObject.put("type",
							index > 0 ? type.substring(index + 1) : type);
					if (index > 0 && type.substring(index + 1).equals("Date")) {
						Date value = (Date) methods[i].invoke(o, null);
						if (value != null) {
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd");
							String str = sdf.format(value);
							jsonObject.put("value", str);
							jsonArray.put(jsonObject);
						}
					} else {
						Object object = methods[i].invoke(o, null);
						if (object != null) {
							jsonObject.put("value", object);
							jsonArray.put(jsonObject);
						}
					}

				}
			}
			_class = _class.getSuperclass();
		}
		return jsonArray;
	}


转载于:https://my.oschina.net/guopengfei/blog/479135

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值