论坛首页 Java企业应用论坛

如何获得pojo中嵌套属性的类型

浏览 7775 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-05-01   最后修改:2012-05-02
有没有一个辅助包,用来获取某个类中的嵌套属性的类型?

比如有个类
public class Employee{

  private String name;
  private Dept   dept;

  get/set 方法省略。。。
}

public class Dept{

  private String deptno;
  private String deptName;

  get/set 方法省略。。。

}

现在就知道 Employee类名 和 dept.deptName字符串 ,如何获取deptName的类型???

只是想问有没有现成的工具类可以用?

BeanWrapperImpl bw = new BeanWrapperImpl(Employee.class);   的 bw.getPropertyType("dept.deptName") 会出错,BeanUtils也是同样的问题。

我现在是通过反射一步一步的调用getDept()、getDeptName来获取的,有没有直接可以用的方法呢?


我给大家说一下我现在的做法:

public static Object getPropertyValue(Class<?> queryClass, String name) {
		String property = name.substring(name.indexOf(".")+1);
		String properties[] = property.split("\\.");
		Class<?> propertyClass = null;
		for(int i=0;i<properties.length;i++){
			if(i==0){
				propertyClass = getClassPropertyType(queryClass,properties[0]);
			}else{
				propertyClass = getClassPropertyType(propertyClass,properties[i]);
			}
		}
                return propertyClass;
	}


private static Class<?> getClassPropertyType(Class<?> clazz, String propertyName) {
		String methodName = "get" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
		try {
			return clazz.getMethod(methodName, null).getReturnType();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}



Class propertyType = getPropertyValue(Empley.class, "t.dept.deptName");

已经实现了,不过就是想问问大家有没有现成的方法可以用。
   发表时间:2012-05-02  
怎么这么多人看,没有回复的?

提点意见也可以啊!
0 请登录后投票
   发表时间:2012-05-02  
private Dept   dept=new Dept()

再用beanutils 的 PropertyUtils
0 请登录后投票
   发表时间:2012-05-02  
char1st 写道
private Dept   dept=new Dept()

再用beanutils 的 PropertyUtils



现在的需求是,不能明确知道嵌套的到底是哪个类,只知道最开始的类名和其属性的.表达式。

所以你上面的方法不通用!
0 请登录后投票
   发表时间:2012-05-02  
我是说你要在Employee里面初始化Dept  。之后再getPropertyType("dept.deptName")就不会出错。
0 请登录后投票
   发表时间:2012-05-02  
char1st 写道
我是说你要在Employee里面初始化Dept  。之后再getPropertyType("dept.deptName")就不会出错。



这个方法应该是可以,但不符合我的要求

还是不能对pojo类做任何改动。
0 请登录后投票
   发表时间:2012-05-02  
Employee e=new Employee();

e.setDept(new Dept());


PropertyUtils.getPropertyType(e, "dept.deptName").getName();




这样可以了 ,嵌套出错的原因是e 的属性dept的值是null,所以要在传到 getPropertyType方法中之前让dept不为null就行了。
0 请登录后投票
   发表时间:2012-05-02  
为什么不用泛型?
0 请登录后投票
   发表时间:2012-05-02  
递归啊递归
0 请登录后投票
   发表时间:2012-05-02  
我觉得没必要每次都动态去获取(反射很耗性能的),维护一个map,在最开始的时候遍历一次,把对应属性缓存起来,这个数据量应该大不到哪去,格式outter.inner.property_name(key) - type(value)
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics