标签:turn 类类型 nts type exce print 简单 for exception
public class TestFactory {
/**
*
*/
private static Map<String, TestInterface> beanMap = ContextUtil.getContext().getBeansOfType(TestInterface.class, false, false);
public static TestInterface getInstance(String infType) {
TestInterface curInstance = null;
for (String beanName : beanMap.keySet()) {
TestInterface instance = beanMap.get(beanName);
if (instance.getType() == null)
throw new RuntimeException("接口实现类类型不可以为空");
else {
if (infType.equals(instance.getType())) {
curInstance = instance;
break;
}
}
}
return curInstance;
}
}
根据Spring
上下文得到某个接口的实现类。
public class ContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ContextUtil.context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
public interface TestInterface<T> {
String getType();
void testFunc(T t);
}
TestInterface
的一个实现类public class TestInterfaceImpl implements TestInterface<String> {
@Override
public String getType() {
return "1";
}
@Override
public void testFunc(String s) {
System.out.println("TestInterfaceImpl -- 01");
}
}
标签:turn 类类型 nts type exce print 简单 for exception
原文地址:https://www.cnblogs.com/imisty/p/11227983.html