JAVA高级---自定义注解、反射

1.自定义注解 Component:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
}

2.用maven在pom.xml中导入 反射工具包reflections:

    <dependencies>
        <dependency>
        
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
            
        </dependency>
    </dependencies>

3.另外创建个类:

public class Application {
   
    static {
        //通过Reflections反射工具包,获得所有添加Component注解的类
        Reflections rs = new Reflections("com/wn/test/Component.java");

        //获取到 带Component注解  的all类
        Set<Class<?>> classSet = rs.getTypesAnnotatedWith(Component.class);

        //创建存放 类的实例  的集合<类名,实例对象>
        Map<String,Object> myMap=new HashMap<String,Object>();

        for (Class<?> aClass : classSet) {
        //扩展:通过对象 先取得类 再取得类名——dog.getClass().getSimpleName()
        //通过类 取得类名:
            String leiming = aClass.getSimpleName();
            try {
                Object obj = aClass.newInstance();
                myMap.put(leiming,obj);
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }

    }
}
发布了13 篇原创文章 · 获赞 7 · 访问量 1242

猜你喜欢

转载自blog.csdn.net/weixin_45881192/article/details/104084274