重庆传智播客吧 关注:15贴子:75
  • 0回复贴,共1

模拟Spring生成对象(下)

只看楼主收藏回复

//根据路径生成对象
private static void creatBeanByPaht(List<String> paths){
//beanMaps
for (String path : paths) {
try {
path = path.replace(".","/");
Enumeration<URL> resources = Analyze.class.getClassLoader().getResources(path);
path = path.replace("/","\\");
while(resources.hasMoreElements()){
String fileRealPath = resources.nextElement().getPath();
File file = new File(fileRealPath);
if(file!=null && file.listFiles().length > 0){
File[] files = file.listFiles();
for (File tempFile : files) {
if(tempFile.isFile() && tempFile.getName().contains(".class")){
String tempFilePath = tempFile.getAbsolutePath().substring(tempFile.getAbsolutePath().indexOf(path));
int dropIndex = tempFilePath.indexOf(".");
String fileName = tempFilePath.substring(0,dropIndex).replace("\\",".");
try {
Class<?> clazz = Class.forName(fileName);
//判断这个类不是一个接口 或者抽象类 如果不是就 生成对象
if(!Modifier.isInterface(clazz.getModifiers()) && !Modifier.isAbstract(clazz.getModifiers())){
if(clazz.isAnnotationPresent(MyCompoment.class) || clazz.isAnnotationPresent(MyController.class) || clazz.isAnnotationPresent(MyService.class) || clazz.isAnnotationPresent(MyDao.class)){
String className = "";
MyCompoment myCompoment = clazz.getAnnotation(MyCompoment.class);
if(myCompoment != null){
className = myCompoment.value();
}
MyController myController = clazz.getAnnotation(MyController.class);
if(myController != null){
className = myController.value();
}
MyService myService = clazz.getAnnotation(MyService.class);
if (myService != null){
className = myService.value();
}
MyDao myDao = clazz.getAnnotation(MyDao.class);
if(myDao != null){
className = myDao.value();
}
//如果没有设置类名 就默认使用类名 首字母小写
if(className.equals("")){
className = clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1);
className = className.substring(0,1).toLowerCase() + className.substring(1);
}
//创建对象
Object obj = clazz.newInstance();
beanMaps.put(className,obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


1楼2018-09-12 09:32回复