返回自己和超类的 public 字段、方法、构造器
getFields()
getMethods()
getConstructors() 超类没返回
返回自己的所有 字段、方法、构造器
getDeclaredFields()
getDeclaredMethods()
getDeclaredConstructors()
package cn.ycx.common.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 类 * * @author: ycx * @date: 2022-5-21 * @since 0.0.1 */ public class YReflect { public static void main(String[] args) throws Exception { Class c = Class.forName("cn.ycx.common.reflect.Student"); System.out.println("自己和超类的"); // 自己和超类的 public 字段 Field[] fields = c.getFields(); for (Field field : fields) { System.out.println(field.getName()); } // 自己和超类的 public 方法 Method[] methods = c.getMethods(); for (Method method : methods) { System.out.println(method.getName()); } // 自己和超类的 Constructor 方法 Constructor[] constructors = c.getConstructors(); for (Constructor constructor : constructors) { System.out.println(constructor.getName()); } System.out.println("自己的"); // 自己的 public 字段 Field[] selfFields = c.getDeclaredFields(); for (Field field : selfFields) { System.out.println(field.getName()); } // 自己的 public 方法 Method[] selfMethods = c.getDeclaredMethods(); for (Method method : selfMethods) { System.out.println(method.getName()); } // 自己的 Constructor 方法 Constructor[] selfConstructors = c.getDeclaredConstructors(); for (Constructor constructor : selfConstructors) { System.out.println(constructor.getName()); } } } class Person { public Person() {} public Person(String p) {} private String personPrivateField = "personPrivateField"; protected String personProtectedField = "personProtectedField"; public String personPublicField = "personPublicField"; private String personPrivateMethod() { System.out.println("personPrivateMethod"); return "personPrivateMethod"; } protected String personProtectedMethod() { System.out.println("personProtectedMethod"); return "personProtectedMethod"; } public String personPublicMethod() { System.out.println("personPublicMethod"); return "personPublicMethod"; } } class Student extends Person { public Student() {} public Student(String s) {super(s);} private String studentPrivateField = "studentPrivateField"; protected String studentProtectedField = "studentProtectedField"; public String studentPublicField = "studentPublicField"; private String studentPrivateMethod() { System.out.println("studentPrivateMethod"); return "studentPrivateMethod"; } protected String studentProtectedMethod() { System.out.println("studentProtectedMethod"); return "studentProtectedMethod"; } public String studentPublicMethod() { System.out.println("studentPublicMethod"); return "studentPublicMethod"; } }