JAVA Advanced --- custom annotations, reflection

1. custom annotation Component:

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

2. Import reflection Kit maven reflections used in pom.xml:

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

3. In addition to create a class:

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();
            } 
        }

    }
}
Published 13 original articles · won praise 7 · views 1242

Guess you like

Origin blog.csdn.net/weixin_45881192/article/details/104084274