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 @ 2022-10-30 23:22  寒小韩  阅读(657)  评论(0编辑  收藏  举报