下面我们来看一下如何获取反射类中的构造方法
public static void printConstructors(Object r) {
Class c = r.getClass();// 获取指定类的类名
String className = c.getName();
try {
// 获取指定类的构造方法
Constructor[] theConstructors = c.getConstructors();
for (int i = 0; i < theConstructors.length; i++) {
// 获取指定构造方法的参数的集合
Class[] parameterTypes = theConstructors[i].getParameterTypes();
System.out.print(className + "(");
for (int j = 0; j < parameterTypes.length; j++)
System.out.print(parameterTypes[j].getName() + " ");
System.out.println(")");
}
} catch (Exception e) {
e.printStackTrace();
}
}
获取反射类的接口
public static void printInterfaceNames(Object
o) {
Class c = o.getClass();
//获取反射类的接口
Class[] theInterfaces = c.getInterfaces();
for(int i=0; i<theInterfaces.length; i++)
System.out.println(theInterfaces[i].getName());
//获取反射类的父类(超类)
Class theSuperclass = c.getSuperclass();
System.out.println(theSuperclass.getName());
}
获取反射类的超类(递归方法)
Class c = o.getClass();
String obj=c.getName();
if(!"java.lang.Object".equals(obj)){
Class theSuperclass = c.getSuperclass();
list.add(obj);
getSuperClass(theSuperclass,list);
}
}
field.setAccessible(true);//设置访问私有属性的方法
Class clas = null;
try {
clas = Class.forName(list.get(i).toString());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
Field[] fields = clas.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);//设置访问私有属性的方法
String key = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (Exception e) {
e.printStackTrace();
}
if (!"".equals(value) && value != null) {
if (value instanceof String) {
typeObj.setString(key, (String) value);
} else if (value instanceof Boolean) {
typeObj.setBoolean(key, (Boolean) value);
} else if (value instanceof Double) {
typeObj.setDouble(key, (Double) value);
} else if (value instanceof IDfId) {
typeObj.setId(key, (IDfId) value);
} else if (value instanceof Integer) {
typeObj.setInt(key, (Integer) value);
} else if (value instanceof IDfTime) {
typeObj.setTime(key, (IDfTime) value);
} else if (value instanceof IDfValue) {
typeObj.setValue(key, (IDfValue) value);
}
}
}