1:反射获取Class类的三种方法
- 通过Class的静态方法获取:Class class = Class.forName(“类的路径:包名.类名”)
- 通过运行时类的对象获取:Person p = new Person(); Class clazz = p.getClass();
- 调用运行时类本身的.class属性:Class class = String.class; //String类的类类型 (String类的字节码)
2:反射获取类名、构造方法、方法和域
建立一个类:
package reflect; /** * @ClassName Student * @Description TODO * @Author Kikityer * @Date 2018/11/7 11:10 * @Version 1.0.0 **/ public class Student { private String namee; private Integer age; private String grage; private Integer studentNum; public Student() { } public Student(String namee) { this.namee = namee; } public Student(String namee, Integer age) { this.namee = namee; this.age = age; } public Student(String namee, Integer age, String grage) { this.namee = namee; this.age = age; this.grage = grage; } public Student(String namee, Integer age, String grage, Integer studentNum) { this.namee = namee; this.age = age; this.grage = grage; this.studentNum = studentNum; } protected void study(){ } public String getNamee() { return namee; } public void setNamee(String namee) { this.namee = namee; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGrage() { return grage; } public void setGrage(String grage) { this.grage = grage; } public Integer getStudentNum() { return studentNum; } public void setStudentNum(Integer studentNum) { this.studentNum = studentNum; } }
测试类:
package reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * @ClassName ReflectTest * @Description TODO * @Author Kikityer * @Date 2018/11/7 11:15 * @Version 1.0.0 **/ public class ReflectTest { public static void main(String[] args) { Class aClass; { try { aClass = Class.forName("reflect.Student"); System.out.println("类的完整类名为:"+ aClass.toString()); System.out.println("类的类名为:"+ aClass.getSimpleName()); System.out.println("------------------------------"); Constructor[] constructors = aClass.getDeclaredConstructors(); for (Constructor cons : constructors){ System.out.println(cons.getName()); System.out.println(cons.getModifiers()); /** * getModifiers()方法返回int类型值表示该字段的修饰符。 * PUBLIC: 1 * PRIVATE: 2 * PROTECTED: 4 * STATIC: 8 * FINAL: 16 * SYNCHRONIZED: 32 * VOLATILE: 64 * TRANSIENT: 128 * NATIVE: 256 * INTERFACE: 512 * ABSTRACT: 1024 * STRICT: 2048 */ } Constructor[] constructors1 = aClass.getConstructors(); for (Constructor cons1 : constructors1){ System.out.println(cons1.getName()); System.out.println(cons1.getModifiers()); } System.out.println("------------------------------"); Method[] methods = aClass.getDeclaredMethods(); for (Method method : methods){ System.out.println(method.getName()); System.out.println(method.getModifiers()); } System.out.println("------------------------------"); Field[] fields = aClass.getDeclaredFields(); for (Field field: fields){ System.out.println(field.getName()); System.out.println(field.getModifiers()); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } }