com.spring.boxes.dollar.support.graphql.GraphqlInvoker Maven / Gradle / Ivy
The newest version!
package com.spring.boxes.dollar.support.graphql;
import graphql.schema.DataFetchingEnvironment;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.Objects;
public class GraphqlInvoker {
public static String[] splitInvokerService(String service) {
Assert.isTrue(StringUtils.isNotBlank(service), "目标方法为空");
String[] arr = StringUtils.split(service, "#");
Assert.isTrue(ArrayUtils.getLength(arr) == 2, "方法格式配置错误");
return arr;
}
public static Object invokeWithSpringContext(ApplicationContext applicationContext,
String serviceInvoker, DataFetchingEnvironment environment) {
String[] invoker = splitInvokerService(serviceInvoker);
return invokeWithSpringContext(applicationContext, invoker[0], invoker[1], environment);
}
public static Object invokeWithSpringContext(ApplicationContext applicationContext,
String beanName, String methodName, DataFetchingEnvironment environment) {
// 根据参数和反射动态调用
Class> clazz = applicationContext.getBean(beanName).getClass();
Object classBean = applicationContext.getBean(beanName);
Method method = ReflectionUtils.findMethod(clazz, methodName, DataFetchingEnvironment.class);
Assert.isTrue(Objects.nonNull(method), "invoke method is null");
return ReflectionUtils.invokeMethod(method, classBean, environment);
}
public static Object invokeWithClassName(String classMethod, DataFetchingEnvironment environment) {
String[] invoker = splitInvokerService(classMethod);
String className = invoker[0];
String methodName = invoker[1];
try {
Class> clazz = Class.forName(className);
Method method = ReflectionUtils.findMethod(clazz, methodName, DataFetchingEnvironment.class);
Assert.isTrue(Objects.nonNull(method), "invoke method is null");
Object classBean = clazz.getDeclaredConstructor().newInstance();
return ReflectionUtils.invokeMethod(method, classBean, environment);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy