注解的小案例

1、定义一个注解

import java.lang.annotation.*;

/**
 * 指定需要执行的类名称和方法名称
 */
@Target(ElementType.TYPE) // 使用的位置
@Retention(RetentionPolicy.RUNTIME) // 保留的阶段
@Documented // 生成javaDoc是否保留
@Inherited // 子类是否继承
public @interface Pro {

    String className();

    String methodName();
}

2、使用注解

import com.erik.anno.Pro;

import java.lang.reflect.Method;

/**
 * ssssswdwd
 *
 * @author : erik
 */
@Pro(className = "com.erik.Yes", methodName = "eat")
public class Index {
    public static void main(String[] args) throws Exception {
        // 解析注解
        Class<Index> indexClass = Index.class;
        Pro annotation = indexClass.getAnnotation(Pro.class);
        String className = annotation.className();
        String methodName = annotation.methodName();
        Class<?> aClass = Class.forName(className);
        Method method = aClass.getMethod(methodName);
        // 实例化Class
        Object o = aClass.newInstance();
        method.invoke(o);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容