反射_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);
        }
    }
}
复制代码

运行结果:

 

posted @   ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示