只为测试反射机制,一般开发中不会这样
class ReflexTest4 {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//创建Class实例,并创建对象
Class<Person> personClass = Person.class;
Constructor<Person> constructor = personClass.getConstructor();//一般都需要有Public的空参的构造器
Person person = constructor.newInstance();
System.out.println(person.toString());
//获取属性结构
//getFields()获取当前运行类及其父类的声明为public访问权限的属性
Field[] fields = personClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("***************************");
Field[] declaredFields = personClass.getDeclaredFields();//获取当前运行时类声明的所有属性(不包含父类中声明的属性)
for (Field declaredField : declaredFields) {
//权限修饰符
int modifiers = declaredField.getModifiers();
//Modifier.toString(modifiers)可以将对应的数组转为对应的权限修饰符的字符串
System.out.print(Modifier.toString(modifiers)+" ");
//getName()返回属性的变量名
System.out.println(declaredField.getName());
}
System.out.println("***************************");
//getMethods()获取当前运行类及其父类的声明为public访问权限的方法
Method[] methods = personClass.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println("***************************");
//获取当前运行时类声明的所有方法(不包含父类中声明的方法)
//权限修饰符 返回值类型 方法名(形参类型 形参名)
Method[] declaredMethods = personClass.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
//获取方法声明的注解
Annotation[] declaredAnnotations = declaredMethod.getDeclaredAnnotations();
for (Annotation declaredAnnotation : declaredAnnotations) {
System.out.println(declaredAnnotation);
}
//输出权限修饰符
int modifiers = declaredMethod.getModifiers();
System.out.print(Modifier.toString(modifiers)+" ");
//输出返回值类型
Class<?> returnType = declaredMethod.getReturnType();
System.out.print(returnType.toString()+" ");
System.out.print(declaredMethod.getName()+"(");
// System.out.println(declaredMethod);
//形参列表
Class<?>[] parameterTypes = declaredMethod.getParameterTypes();
if (parameterTypes.length>0){
for(int i=0;i<parameterTypes.length;i++){
System.out.print(parameterTypes[i]+" agrs"+i);
if (i+1!=parameterTypes.length){
System.out.println(",");
}
}
}
System.out.print(")");
//抛出的异常
Class<?>[] exceptionTypes = declaredMethod.getExceptionTypes();
if (exceptionTypes.length>0){
System.out.print("throws ");
for(int i=0;i<exceptionTypes.length;i++){
System.out.print(exceptionTypes[i].getName());
if (i+1!=exceptionTypes.length){
System.out.print(",");
}
}
}
System.out.println();
}
}
}
运行结果