注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。作用分类:

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名注册、网络空间、营销软件、网站建设、秀山土家族苗族网站维护、网站推广。
注解不会改变程序的语义,只是作为注解(标识)存在,我们可以通过反射机制编程实现对这些元数据(用来描述数据的数据)的访问
@java.lang.annotation.Retention定义注解的有效时期
相关参数:RetentionPolicy.SOURCE: 编译期生效,编译器会丢弃,编译后的class文件并不包含该注解 RetentionPolicy.CLASS: 注解会被保留在class文件中,但是运行期不会生效,被JVM忽略 RetentionPolicy.RUNTIME: 注解会被保留在class文件中,并且会在运行期生效,JVM会读取
@Target定义注解作用对象,也就是注解是可以用在类、方法、参数还是其他等待
相关参数:ElementType.TYPE: 该注解只能运用到Class, Interface, enum上 ElementType.FIELD: 该注解只能运用到Field上 ElementType.METHOD: 该注解只能运用到方法上 ElementType.PARAMETER: 该注解只能作用在参数上 ElementType.CONSTRUCTOR: 该注解只能作用在构造方法上 ElementType.LOCAL_VARIABLE: 该注解作用在地变量或catch语句 ElementType.ANNOTATION_TYPE: 该注解只能作用在注解上 ElementType.PACKAGE: 该注解只能用在包上
Java中常见的内置注解:
如果某个注解上有@Inherited注解,当查找该类型的注解时,会先查找目标类型是否存在注解,如果有,直接返回;否则,继续在父类上寻找注解, 停止的条件为在父类上找到该类型的注解或者父类为Object类型。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface ClassMapper {
}下面的示例中,如果ClassMapper没有@Inherited修饰,则返回null
Child.class.getAnnotation(ClassMapper.class);
@Slf4j
public class ExtendAnnotationTests {
    @ClassMapper
    public class Demo { }
    public class Child extends Demo{  }
}
我们知道,在Spring中,注解@Service与@Component都是用来标记类,交由Spring容器管理其对应的Bean,是结果是等效的。主要是Spring将注解和元注解进行了合并
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Mapper {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Mapper
public @interface ClassMapper {
}通过下面的方法可以拿到元注解,从而进行其他扩展。
public class Tests {
    @Test
    public void test(){
        ClassMapper classMapper = Demo.class.getAnnotation(ClassMapper.class);
        log.info("classMapper: {}", classMapper);
        Mapper mapper = classMapper.annotationType().getAnnotation(Mapper.class);
        log.info("mapper: {}", mapper);
    }
}
示例主要针对@java.lang.annotation.Retention参数的三种情况,了解注解是生效时期:
该示例实现通过自定义注解@SystemProperty,实现为对象字段设置系统属性
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface SystemProperty {
    String value();
}
主要作用是在运行时解析注解@SystemProperty,并实现系统属性注入的逻辑。前面说到,注解的作用主要是标记,针对RetentionPolicy.RUNTIME类型的注解,一般是在运行时 通过反射实现注解标识的类、字段或方法等等元数的处理过程。
ObjectFactory是一个对象生产工厂,这样我们可以在运行期解析目标对象中的是否有@SystemProperty标识的字段,并对该字段进行值的设定,这样式该注解设计的初衷,但是 实现需要我们根据需求实现
@Slf4j
public class ObjectFactory {
    // 省略 ...
  
    public static  T getObject(Class type, Object... args){
        Constructor constructor = findTypeConstructor(type, args);
        T object = constructor.newInstance(args);
        // 通过反射找到对象中@SystemProperty的字段,并根据其设置参数将系统属性设定到该对象字段中
        processFieldAnnotations(object, type, SystemProperty.class);
        return object;
    }
    
    // 省略 ...  
}   
@Slf4j
public class RuntimeAnnotationTests {
    @Test
    public void run(){
        Demo demo = ObjectFactory.getObject(Demo.class);
        log.info(">> result: {}", demo.user);
    }
    @Data
    public static class Demo{
        @SystemProperty("user.name")
        private String user;
    }
}
该示例主要实现,编译器判断通过@FinalClass注解标记的类是否为final类型
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
@Documented
public @interface FinalClass {
}
@SupportedAnnotationTypes({FinalClassProcessor.FINAL_CLASS})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class FinalClassProcessor extends AbstractProcessor {
    public static final String FINAL_CLASS = "com.sucl.blog.jdk.annotation.compile.FinalClass";
    
    @Override
    public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
        TypeElement annotationType = this.processingEnv.getElementUtils().getTypeElement(FINAL_CLASS);
        if( annotationType != null ){
            for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
                if( element instanceof TypeElement ){
                    TypeElement typeElement = (TypeElement) element;
                    if( !typeElement.getModifiers().contains(Modifier.FINAL) ){
                        String message = String.format("类【%s】必须为final类型", typeElement);
                        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
                    }
                }
            }
        }
        return true;
    }
}
      com.google.auto.service 
      auto-service 
      1.1.0 
     3.2 在Processor通过注解@AutoService标识
@AutoService(Processor.class)
public class FinalClassProcessor extends AbstractProcessor{}
    org.apache.maven.plugins 
    maven-compiler-plugin 
    
        
            
                com.sucl.blog.jdk.annotation.compile.FinalClassProcessor
             
         
     
 
打包,在项目中引入该jar,定义一个类,类似下面这样,当该类没有final修饰时,通过maven install命令,可以看到控制台打印自定义的错误信息
@FinalClass
public final class ProcessorFinder {}注意
RetentionPolicy.CLASS的使用需要达打成jar包才行,不然无法再编译时处理注解
RetentionPolicy.SOURCE
定义一个注解,通过打包后的结果观察该注解的状态
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@Documented
public @interface System {
    
}
@System
public class SystemProvider {
}
        
            org.apache.maven.plugins 
            maven-source-plugin 
            3.2.1 
            
                
                    attach-sources 
                    
                        jar 
                     
                 
             
         
     
在基于Spring Boot开发项目时,我们一般通过 @ConfigurationProperties 配合 spring-boot-configuration-processor,可以实现在项目打包时 生成一个spring-configuration-metadata.json的配置描述文件,这样在编写application.yml配置时,就会得到配置提示,其实现方式就是基于 ConfigurationMetadataAnnotationProcessor,
注解本身没有含义,主要作用是标记目标元素,后续拿到改标识的元数据,进行一系列的处理。注解的使用是非常广泛的,各种框架中都使用频繁,基于注解可以将很多抽象功能提取出来,通过简单 的标识来实现各种复杂的功能。
                文章题目:Java中注解的高级用法
                
                当前URL:http://www.csdahua.cn/qtweb/news5/61655.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网