一、Java通过反射获取对象,执行方法
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Class clzss = Class.forName("xxx.xxx.xx.className");
Object obj = clzss.getDeclaredConstructor().newInstance();
Method method = clzss.getMethod("xxxMethod");
method.invoke(obj);
}
}
二、springboot通过反射获取bean对象,执行方法
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {XXXXXXXApplication.class})
public class Test {
@Autowired
private ApplicationContext applicationContext;
@org.junit.Test
public void TestSpringBean() {
try {
Class<?> cls = Class.forName("xxx.xxx.xx.className");
Object bean = applicationContext.getBean(cls);
Method method = cls.getMethod("xxxMethod", String.class);
String data = "{\"name\":\"cs\"}";
method.invoke(bean, data);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}