我有一个跟随类,我试图通过反射实例化,然后自动实例化它的字段“databaseService”
@Controller
public class BaseController {
@AutoInstantiate
private DatabaseService databaseService;
@AfterSetup
public void initialize() {
System.out.println("Testing " + databaseService.getEntry());
}
}
我的简单类我正在尝试自动实例化
public class DatabaseService {
public DatabaseService() {}
public String getEntry() {
return "I'm working! ";
}
}
我想做什么
public class Instantiator {
private static void start() {
Reflections reflections = new Reflections("com");
Class<?> clazz = reflections.getTypesAnnotatedWith(Controller.class)[0];
//Assume 'clazz' is 'BaseController' (the parent class of DatabaseService)
for(Field field : clazz.getDeclaredFields()) {
if(field.isAnnotationPresent(AutoInstantiate.class)) {
try {
field.setAccessible(true);
Object autowiredObject = field.getType().newInstance();
//HERES WHERE IT ALWAYS FAILS
field.set(clazz, autowiredObject);
}
catch(Exception e) {
logger.severe("Failure invoking class " + clazz.getName() + " Problem : " + e.getMessage());
}
}
}
}
}
和简单的主
public class App {
public static void main(String[] args) throws Exception {
Instantiator.start();
}
}
问题严重:调用类 com.controller.BaseController 失败 问题:无法将 com.service.DatabaseService 字段 com.controller.BaseController.databaseService 设置为 java.lang.Class
总体问题:我不确定如何将实例化的类对象(DatabaseService)设置回它的父类(BaseController)
蛊毒传说
相关分类