public interface HelloService {
String sayHello(String name);
}
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String msg) {
int i = 1 / 0;
return "你好, " + msg;
}
}
反射获取 通过配置文件获取
ublic class ServicesFactory {
static Properties properties;
static Map<Class<?>, Object> map = new ConcurrentHashMap<>();
static {
try (InputStream in = Config.class.getResourceAsStream("/application.properties")) {
properties = new Properties();
properties.load(in);
Set<String> names = properties.stringPropertyNames();
for (String name : names) {
if (name.endsWith("Service")) {
Class<?> interfaceClass = Class.forName(name);
Class<?> instanceClass = Class.forName(properties.getProperty(name));
map.put(interfaceClass, instanceClass.newInstance());
}
}
} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new ExceptionInInitializerError(e);
}
}
public static <T> T getService(Class<T> interfaceClass) {
return (T) map.get(interfaceClass);
}
}
application.properties配置文件标记 方法路径
cn.itcast.server.service.HelloService=cn.jinzhu.netty.server.service.HelloServiceImpl
测试
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
RpcRequestMessage message = new RpcRequestMessage(
1,
"cn.jinzhu.netty.server.service.HelloServiceImpl",
"sayHello",
String.class,
new Class[]{String.class},
new Object[]{"张三"}
);
HelloService service = (HelloService)
ServicesFactory.getService(Class.forName(message.getInterfaceName()));
Method method = service.getClass().getMethod(message.getMethodName(), message.getParameterTypes());
Object invoke = method.invoke(service, message.getParameterValue());
System.out.println(invoke);
}