欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

通过反射获取类的结构小栗子

时间:2023-06-14

public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException { Class student = Student.class; //获取类的名字 System.out.println(student.getName());//获取包名+类名 System.out.println(student.getSimpleName());//获取类名 System.out.println("----------------------------------"); //值获取public属性 for (Field field : student.getFields()) { System.out.println(field); } //获取所有的属性 for (Field declaredField : student.getDeclaredFields()) { System.out.println(declaredField); } Field id = student.getDeclaredField("id"); System.out.println(id); System.out.println("---------------------------------"); //获得本类及其父类的所有方法 for (Method method : student.getMethods()) { System.out.println("method "+method); } //获得本类的所有方法 for (Method declaredMethod : student.getDeclaredMethods()) { System.out.println(declaredMethod); } System.out.println("---------------------------------"); //获得指定方法 Method getId = student.getMethod("getId", null); Method getAge = student.getMethod("getAge", null); Method setName = student.getMethod("setName", String.class); System.out.println(getId); System.out.println(getAge); System.out.println(setName); System.out.println("---------------------------------"); //获得所有的构造器 for (Constructor constructor : student.getConstructors()) { System.out.println(constructor); } for (Constructor declaredConstructor : student.getDeclaredConstructors()) { System.out.println(declaredConstructor); } //获取指定的构造器 Constructor declaredConstructor = student.getDeclaredConstructor(Integer.class, String.class, int.class); System.out.println(declaredConstructor); }

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。