反射获取成员方法并使用
package ClassTest.ClassFieldsTest; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * FileName: ReflectDemo03 * Author: lps * Date: 2022/4/11 19:28 * Sign:刘品水 Q:1944900433 * //方法 getMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象, * // 该对象反映由该 Class对象表示的类或接口的指定公共成员方法。 * //方法[] getMethods() 返回一个包含 方法对象的数组, * // 方法对象反映由该 Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象以及从超类和超级接口继承的类。 * //方法 getDeclaredMethod(String name, Class<?>... parameterTypes) * // 返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 Class对象。 * //方法[] getDeclaredMethods() 返回一个包含 方法对象的数组, * // 方法对象反映由 Class对象表示的类或接口的所有声明方法,包括public,protected,default(package)访问和私有方法 * ,但不包括继承方法。 */ public class ReflectDemo03 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { Class<?> c = Class.forName("ClassTest.ClassTest01.Student"); //Method[] methods = c.getMethods(); Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { System.out.println(method); } System.out.println("--------"); //public void method1() Method m = c.getMethod("method1"); Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); //方法在类或接口上提供有关单一方法的信息和访问权限。 反映的方法可以是类方法或实例方法(包括抽象方法)。 //Object invoke(Object obj, Object... args) 在具有指定参数的指定对象上调用此 方法对象表示的基础方法。 m.invoke(obj); } }
package ClassTest.ClassTest01; /** * FileName: Student * Author: lps * Date: 2022/4/11 15:22 * Sign:刘品水 Q:1944900433 */ public class Student { private String name; int age; public String adress; public Student() { } private Student(String name) { this.name = name; } Student(String name, int age) { this.name = name; this.age = age; } public Student(String name, int age, String adress) { this.name = name; this.age = age; this.adress = adress; } private void function() { System.out.println("function"); } public void method1() { System.out.println("method"); } public void method2(String s) { System.out.println("method:" + s); } public String method3(String s, int i) { return s + "," + i; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", adress='" + adress + '\'' + '}'; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)