package com.loan.system.utils.logUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

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

/*
 * 反射工具类
 *
 * @author chen
 * @date 2019/10/01
 * */
@Component
public class ServiceHelper {

    @Autowired
    ApplicationContext applicationContext;

    public Object invoke(String sname, String mname) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object gteBean = applicationContext.getBean(sname);
        Class objClass = gteBean.getClass();
        Method getMethod = objClass.getMethod(mname, Integer.class);
        return getMethod.invoke(gteBean, 8);
    }

    /*
     * 动态获取bean，反射执行service的方法
     *
     * @param sname 被获取的bean
     * @param mname bean中的方法名
     * @param id    查询条件
     * */
    public Object getBeanById(String sname, String mname, Long id) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object gteBean = applicationContext.getBean(sname);
        Class objClass = gteBean.getClass();
        Method getMethod = objClass.getMethod(mname, Long.class);
        return getMethod.invoke(gteBean, id);
    }
}
