题目如下:已知一个包下分别有Student、Teacher、Employee三个Java源文件,请据此实现以下功能:
(1)、自定义一个名为Component的注解,要求该注解只能用于类且代码运行时该注解依然有效
(2)、为Student和Teacher类添加Component注解
(3)、在Application类中定义静态代码块,
该代码块可自动将标记有Component注解修饰的类动态创建对象并放在Map集合中;
(4)然后定义一个名为getBean的static方法,
要求传入参数为Class类实例时返回该Class类对应类的对象,
如果没有Class类对应类的对象,
则引发自定义异常NoSuchBeanDefinitionException异常
并提示“No qualifying bean of type ’
自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
}
使用注解标记需要存入容器的bean
@Component
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
创建文件保存bean包名
例如:packageName=day22.bean
创建Application类
public class Application {
private static Map<Class<?>,Object> map = new HashMap<>();
private Application() {}
static {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(new File("src/day22/applicationContext.properties")));
String packageName = prop.getProperty("packageName");
File f = new File("src/"+packageName.replace(".","/"));
File[] listFiles = f.listFiles();
for (File file : listFiles) {
if(file.getName().endsWith(".java")) {
String className = packageName + "." + file.getName().substring(0, file.getName().length() - 5);
Class<?> c = Class.forName(className);
Component annotation = c.getAnnotation(Component.class);
if(annotation != null) {
map.put(c, c.newInstance());
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static <T> T getBean(Class<T> c){
T t = (T)map.get(c);
if(t == null) {
throw new NoSuchBeanDefinitionException("NoSuchClass");
}
return t;
}
}
创建测试类
public class Test {
public static void main(String[] args) throws Exception {
Student s = Application.getBean(Student.class);
System.out.println(s);
}
}