JAVA通过反射执行某个类的某个方法

JAVA通过反射执行某个类的某个方法

通过反射机制执行方法的关键:

/**
*obj:调用底层方法的对象;
*args:方法执行参数,顺序,可选
*/
public Object invoke(Object obj, Object... args)

示例

在包com.example.reflectdemo.service的类HelloTest

package com.example.reflectdemo.service;

import org.springframework.stereotype.Service;

/**
 * @Desc
 * @Created By lkh
 * @date on 2020/2/28
 */
@Service
public class HelloTest {
    public void sayHello(){
        System.out.println("hello world!");
    }
}

测试类

package com.example.reflectdemo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@SpringBootTest
class ReflectdemoApplicationTests {

    @Test
    void contextLoads() {

        try {
            // 你需要的class
            Class<?> clazz = Class.forName("com.example.reflectdemo.service.HelloTest");
            // 创建对象
            Object instance = clazz.getConstructor().newInstance();
            // 调用方法
            for(Method method :clazz.getMethods()) {
                if("sayHello".equals(method.getName())) {
                    method.invoke(instance);//
                }
                if ("sayHello2".equals(method.getName())) {
                    method.invoke(instance,"李白");
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

执行结果:

李白:hello world!
hello world!
posted @   寒小韩  阅读(685)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示