1.先构建注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bean {
String name() default "";
}
2.根据包名拿到路径下的class文件,同时在根据指定的注解去实例化
public class SpringDemo {
public static void main(String[] args)throws IOException {
String packageName="com.springdemo";
Map excuten = excuten(packageName);
System.out.println(excuten);
}
/*由包名拿到class文件的全路径名*/
public static String getpaths(String packageName){
ClassLoader loader = SpringDemo.class.getClassLoader();
URL resource = loader.getResource(packageName.toString().replace('.', '/'));
String path = resource.getPath();
File file = new File(path);
String absolutePath = file.getAbsolutePath();
return absolutePath;
}
/*字符串的截取,截取为包名的形式 */
public static String packageName(Path path){
String s1 = path.toString();
int com = s1. lastIndexOf("com");
int coms= s1.lastIndexOf(".class");
String packageClassName = s1.substring(com, coms);
String replace = packageClassName.replace('\\', '.');
return replace;
}
//遍历文件目录那到class 文件,并通过反射拿到类中的注解类型。同时创建class 对象
public static Map<String,? extends Object> excuten(String packageName) throws IOException {
Map map = new HashMap<>();
String getpaths = getpaths(packageName);
Path path = Paths.get(getpaths);
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(file.toString().endsWith(".class")){
String packageName = packageName(file);//拿到包路径
try {
Class<?> aClass = Class.forName(packageName);
Bean bean = aClass.getAnnotation(Bean.class);
if (bean!=null){
String name = bean.name();
if (name.length()<1){
name=aClass.getSimpleName();
map.put(name,Class.forName(packageName).newInstance());
}else{
map.put(name,Class.forName(packageName).newInstance());
}
}
}catch (Exception e){
e.printStackTrace();
}
}
return FileVisitResult.CONTINUE;
}
});
return map;
}
}