反射_Class对象功能_获取Constructor-反射_Class对象功能_获取Method
反射_Class对象功能_获取Constructor
Constructor<?>[] getConstructors()
Constructor<T> getConstructor(Class<?>... parameterTypes)
Constructor<?>[] getDeclaredConstructors()
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
Constructor构造方法
创建对象:
T newInstance(Object... initargs)
如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法
忽略访问权限修饰符的安全检查 setAccessible(true):暴力反射
import domain.Person; import java.lang.reflect.Constructor; import java.lang.reflect.Field; public class ReflectDemo3 { public static void main(String[] args) throws Exception { //0、获取Person的Class对象 Class personClass = Person.class; //Constructor<?>[] getConstructors() Constructor constructor = personClass.getConstructor(String.class,int.class); System.out.println(constructor); //创建对象 Object person = constructor.newInstance("张三", 23); System.out.println(person); System.out.println("--------"); Constructor constructor1 = personClass.getConstructor(); System.out.println(constructor1); //创建对象 Object person1 = constructor1.newInstance(); System.out.println(person1); Object o = personClass.getConstructor().newInstance(); System.out.println(o); } }
运行结果:
反射_Class对象功能_获取Method
Method[] getMethods()
Method getMethod(String name, Class<?>... parameterTypes)
Method[] getDeclaredMethods()
Method getDeclaredMethod(String name, Class<?>... parameterTypes)
Method :方法对象:
执行方法:
Object invoke(Object obj,Object... args)
获取方法名称:
String getName:获取方法名
import domain.Person; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectDemo4 { public static void main(String[] args) throws Exception { //0、获取Person的Class对象 Class personClass = Person.class; //获取成员方法 Method eat_method = personClass.getMethod("eat"); Person p = new Person(); //执行方法 eat_method.invoke(p); Method eat_method2 = personClass.getMethod("eat", String.class); //执行方法 eat_method2.invoke(p,"饭"); System.out.println("-------------"); //获取所有public修饰的方法 Method[] methods = personClass.getMethods(); for(Method method : methods){ System.out.println(method); String name = method.getName(); System.out.println(name); } } }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix