反射:通俗点讲就是在运行过程中根据对象找类
以下时反射常用到的一些方法做简单记录( 以person对象为例)
类路径实例化calss类:
public static Object getInstance(String calssName) {
try {
return Class.forName(calssName).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
获取所有方法
public static void getMethods() {
Object obj = getInstance("com.reflect.Person");
Class<? extends Object> cls = obj.getClass();
try {
Method[] methods = cls.getMethods();
for (Method method : methods) {
//方法的参数
Class<?>[] parameterTypes = method.getParameterTypes();
//方法名称
String methodName = method.getName();
//参数个数
int parameterLength = parameterTypes.length;
System.out.println(methodName+" : "+parameterLength);
if(parameterTypes.length>0){
//参数类型
System.out.println(parameterTypes[0].toString());
}
//参数set方法赋值
if(method.getName().startsWith("set")){
method.invoke(obj, "1");
}
}
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
获取所有属性
public static void getFields() {
try {
Object obj = getInstance("com.reflect.Person");
Class<? extends Object> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
//设置属性可访问
field.setAccessible(true);
//属性名称
System.out.println(field.getName());
//属性类型
System.out.println(field.getType());
int modifier = field.getModifiers();
//属性的访问权限
System.out.println(Modifier.toString(modifier));
//属性赋值
field.set(obj, "1");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
获取父类和接口:
public static void getExtendAndInterFaces(Class<? extends Object> cls) {
//获取父类
Class<?> superclass = cls.getSuperclass();
System.out.println(superclass);
//获取接口
Class<?>[] interfaces = cls.getInterfaces();
for (int j = 0; j < interfaces.length; j++) {
System.out.println(interfaces[j]);
}
}