Java系列3---注解

130 阅读1分钟

1、注解(元数据)是什么?

为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后某个时刻非常方便的使用这些数据。

2、能干啥?

JDK1.5内置的三种注解:
    @Override
    @Deprecated
    @SuppressWarnings

3、定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.TYPE})
public @Interface Test{
    
}
元注解:
    @Target:表示该注解用到什么地方
    @Retention:表示需要在什么级别保存该注解信息
    @Documented:将此注解包含在javadoc中
    @Inherited:允许子类继承父类的注解
标记注解:没有元素的注解。

4、使用注解

@Test
public class TestDemo{
    
}

5、注解处理器

通过反射机制处理
public class Main{
    public static void main(String[] args){
        String className = args[0];
        Class cl = Class.forName(className);
        Test test = cl.getAnnotation(Test.class);
        if(test!=null){
            //说明该类使用了Test注解,处理一些事情
        }
    }
}
使用apt处理注解(未完)
注解元素可用类型:
    所有基本类型
    String
    Class
    Enum
    Annotation
    以上类型的数组