取类的所有属性、方法,包括所有父类的属性方法

代码:
/**
* 获取类实例的属性值
*
* @param clazz
*            类名
* @return 类名.属性名=属性类型
*/
public static ArrayList<Field> getClassFields(Class clazz) {
ArrayList<Field> map = new ArrayList<Field>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {

if (field.getName().matches("this[$].*")) {

} else {
map.add(field);
}

}
// if (includeParentClass)
getParentClassFields(map, clazz.getSuperclass());
return map;
}

/**
* 获取类实例的父类的属性值
*
* @param map
*            类实例的属性值Map
* @param clazz
*            类名
* @return 类名.属性名=属性类型
*/
private static ArrayList<Field> getParentClassFields(ArrayList<Field> map, Class clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.getName().matches("this[$].*")) {

} else {
map.add(field);
}

}
if (clazz.getSuperclass() == null) {
return map;
}
getParentClassFields(map, clazz.getSuperclass());
return map;
}

/**
* 获取类实例的方法
*
* @param clazz
*            类名
* @return List
*/
public static List<Method> getMothds(Class clazz) {
List<Method> list = new ArrayList<Method>();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
list.add(method);
}
getParentClassMothds(list, clazz.getSuperclass());

return list;
}

/**
* 获取类实例的父类的方法
*
* @param list
*            类实例的方法List
* @param clazz
*            类名
* @return List
*/
private static List<Method> getParentClassMothds(List<Method> list, Class clazz) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
list.add(method);
}
if (clazz.getSuperclass() == Object.class || clazz.getSuperclass() == null) {
return list;
}
getParentClassMothds(list, clazz.getSuperclass());
return list;
}


测试代码:

/**
* 测试
*
* @param args
*/
@Test
public  void testClassFild() {

// 获取属性
ArrayList<Field> map = SystemTool.getClassFields(Student.class);
for (Field fld : map) {
System.out.println(fld.getName());
}
// 获取方法
List<Method> methods = SystemTool.getMothds(Student.class);
for (Method method : methods) {
System.out.println(method.getName());
}
System.out.println("方法总数:" + methods.size());
}

class Student extends School{
private int age;

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

class School extends Country {
private String schoolName;

public String getSchoolName() {
return schoolName;
}

public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}


}
class Country{

private String countryName;

public String getCountryName() {
return countryName;
}

public void setCountryName(String countryName) {
this.countryName = countryName;
}


}

猜你喜欢

转载自xxqn.iteye.com/blog/2325571