是否可以从字符串中调用接口?
String repName = "package." + modelName + "Repository";
Class<?> repo = Class.forName(repName);
Object obj = repo.getDeclaredConstructor().newInstance();
Method setNameMethod = obj.getClass().getMethod("findById", int.class);
setNameMethod.invoke(obj, 7); // passing 7
这应该适用于常规方法/类,但是如何动态调用接口?
答案 0 :(得分:2)
如果您在spring上下文中进行操作,则可以使用ApplicationContext
-bean:
@Component
class Test {
private final ApplicationContext context;
@Autowired
public Test(ApplicationContext context) {
this.context = context;
}
public void callRepository(String repName) /* here should come some throws declarations */ {
Class<?> type = Class.forName(repName);
Object instance = context.getBean(repName);
type.getMethod("findById", int.class).invoke(instance, 7);
}
}
ApplicationContext
允许您访问每个注册的bean。