Constructorc2= clazz.getConstructor(String.class, int.class, String.class); c2.setAccessible(True); // make private able to access as public Carcar2= (Car)c2.newInstance("Tesla", 10, "white");
privatevoidloadBean(File file)throws Exception { // 1. if it's a folder if(!file.isDirectory()) { return; } // 2. get all contents of folder File[] childrenFiles = file.listFiles(); // 3. if null, or empty, return if(childrenFiles == null || childrenFiles.length == 0) { return; } // 4. if not empty, traverse them for (File child: childrenFiles) { // 4.1 if still a directory, do recursion if(file.isDirectory()) { loadBean(child); } else { // 4.2 it's a file, get package path StringpathWithClass= child.getAbsolutePath().substring(rootPath.length() - 1); // 4.3 is class type file if(pathWithClass.contains(".class")) { // 4.4 if it's class type, replace \ with . StringfullName= pathWithClass.replaceAll("\\\\", ".").replace(".class", ""); // 4.5 if there is @Bean annotation // 4.5.1 get class object Classclazz= Class.forName(fullName); // 4.5.2 if it's not interface if(!clazz.isInterface()) { // 4.5.3 has @Bean Beanannotation= (Bean) clazz.getAnnotation(Bean.class); if(annotation != null) { // 4.5.4 instantiate Objectinstance= clazz.getConstructor().newInstance(); // 4.6 put it into map // 4.6.1 if the class implements interface, use interface as key. if(clazz.getInterfaces().length > 0) { beanFactory.put(clazz.getInterfaces()[0], instance); } else { beanFactory.put(clazz, instance); } } } } } } }
privatevoidloadDi() { // 1. traverse beanFactory Set<Map.Entry<Class, Object>> entries = beanFactory.entrySet(); for (Map.Entry<Class, Object> entry: entries) { // 2. get each object Objectobj= entry.getValue(); Classclazz= obj.getClass(); Field[] declaredFields = clazz.getDeclaredFields(); // 3. travers to get each property of object for (Field field : declaredFields) { // 4. is property has @Di annotation Diannotation= field.getAnnotation(Di.class); if(annotation != null) { // if it is a private property, we need to make it accessible field.setAccessible(true); // 5. if it has, inject the object try { field.set(obj, beanFactory.get(field.getType())); } catch (IllegalAccessException e) { thrownewRuntimeException(e); } } }
} }
And then add UserDao’s add() method to UserService’s add method. to test.