大体思路
- 获取指定文件夹下的所有类
- 遍历所有类检查每一个类有无指定注解
- 如有对应的注解则进行对应的操作
最后返回的是一个map集合
先定义一个Map集合,目的就是通过类名key拿到对应的对象value
private Map<String,Object> map;
Bean注解功能
//获取domain目录路径
String path = getClass().getResource("domain").getPath();
/**获取domain类中的全限定名前缀*/
//去掉前面的的路径
String replace = path.replace(path1, "");
//把 "/" 全部替换为 "."
replace = replace.replace("/", ".");
//最后在末尾加上一个.,即有了类的全限定名的前缀
String main = replace + ".";
//转成文件类型
File file1 = new File(path);
//获取该文件下的所有文件
File[] files1 = file1.listFiles();
获取项目根路径
String path = getClass().getResource(“/”).getPath();
//遍历文件(也就是遍历类)
try {
for (File F : files1) {
/**因为获取到的名字是 对象名.class 所以要进行处理*/
//获取最后一个.所在的索引位置
int i = F.getName().lastIndexOf(".");
//把前面的类名截取出来
String substring = F.getName().substring(0,i);
//设置全限定名的字符串
String newClass = main + substring;
//获取字节码对象
Class<?> aClass = Class.forName(newClass);
//根据字节码对象获取指定注解
boolean annotationPresent1 = aClass.isAnnotationPresent(Component.class);
//如果为false即为没有对应的注解
if(annotationPresent1){
//创建对象并存入Map
Object o = aClass.newInstance();
//名字以获得的类名作为key
map.put(substring,o);
}
Value注解功能
//根据字节码对象获取该对象的所有字段
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
//判断有无该注解
boolean annotationPresent = declaredField.isAnnotationPresent(Value.class);
if (annotationPresent) {
//获取注解设置的值
String value = declaredField.getAnnotation(Value.class).value();
//获取属性名字
String d = declaredField.getName();
/**
* 下面就是内省
*/
//获取属性描述器
BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
//获取所有属性
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor p : propertyDescriptors) {
//对比属性名,如果匹配上那么就设置注解的值
if (d.equals(p.getName())) {
//获取set方法
Method writeMethod = p.getWriteMethod();
//对上面创建出来的对象进行赋值
writeMethod.invoke(map.get(substring),value);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(map);