posts - 397,comments - 0,views - 25332

反射_Class对象功能_获取method

Method:方法对象

  执行方法

   Object invoke(Object obj, Object.... args)

  获取方法名称

   String getName:获取方法名

代码实现:

//获取Person的Class对象
        Class  personClass = Person.class;
        //获取指定名称
        Method method = personClass.getMethod("eat");
        Person person = new Person();
        //执行方法
        method.invoke(person);
复制代码
Method eat = personClass.getMethod("eat", String.class);
        //执行方法
        eat.invoke(person,"饭");
        System.out.println("-----------");

        //获取所有public修饰的方法
        Method[] methods = personClass.getMethods();
        for (Method method1 : methods) {
            System.out.println(method1);
            String name = method1.getName();
            System.out.println(name);
        }
        String name = personClass.getName();
        System.out.println(name);
复制代码

 

 

反射案例

需求:

  写一个框架,可以帮助我们创建任意的对象,并且执行其中任意方法

 

代码:

创建一个properties文间

 

 

 

 

 代码实例:

  

复制代码
 //加载配置文件
        //创建properties
        Properties properties = new Properties();
        //加载配置文件,转换为一个集合
        //获取class目录下的配置文件

        ClassLoader classLoader = ReflectTest.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");
        properties.load(resourceAsStream);
        //获取配置文件中定义的数据
        String className = properties.getProperty("className");
        String methodName = properties.getProperty("methodName");

        //加载该类进内存
        Class aClass = Class.forName(className);
        //创建对象
        Object o = aClass.newInstance();
        //获取方法对象
        Method method = aClass.getMethod(methodName);
        //执行方法
        method.invoke(o);
复制代码

 

posted on   淤泥不染  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示