zoukankan      html  css  js  c++  java
  • Java注解

    注解 Annotation

    什么是注解?

    作用:

    • 不是程序本身, 可以对程序作出解释 (类似注释)
    • 可以被其他程序读取 (如编译器)

    格式:

    • @注释名, 还可添加参数
      如:@SuppressWarnings(value="unchecked")
      

    在哪使用?

    • 附加在 package, class, method, field 等, 相当于添加了额外的辅助信息
    • 可以通过反射机制编程实现对这些元数据的访问

    内置注解

    • @Override : 只适用于修饰方法, 表示打算重写超类的方法
    • @Deprecated : 可修饰方法, 属性和类, 表示不鼓励使用
    • @SuppressWarnings
    package com.guanxing.annotation;
    
    import java.awt.*;
    
    //什么是注解
    public class Test01 extends Object{
    
        //@Override 重写的注解
        @Override
        public String toString() {
            return super.toString();
        }
    
        @Deprecated  //不推荐程序员使用,但可以使用.或者存在风险
        public static void testDep(){
            System.out.println("Deprecated");
        }
    
        @SuppressWarnings("all")  //镇压警告
        public void testSup(){
            List list = new List();
        }
    
        public static void main(String[] args) {
            testDep();  //依旧可以使用
        }
    }
    

    元注解

    • @Target : 用于描述注解的使用范围
    • @Retention : 表示需要在什么级别保存该注释信息, 用于描述注解的生命周期
      • ( SOURCE < CLASS < RUNTIME )
    • @Document : 说明该注解将被包含在 javadoc 中
    • @Inherited : 说明子类可以继承父类中的该注解
    package com.guanxing.annotation;
    
    import java.lang.annotation.*;
    
    //测试元注解
    public class Test02 {
        @MyAnnotation  //Target定义作用范围有METHOD
        public void test01(){
        }
    }
    
    //定义一个元注解
    //Target 表示可作用的地方
    @Target(value = {ElementType.METHOD, ElementType.TYPE})
    
    //Retention 表示在什么地方有效
    @Retention(value = RetentionPolicy.RUNTIME)
    
    //表示是否将注解生成在javadoc中
    @Documented
    
    //表示子类可以继承父类的注解
    @Inherited
    @interface MyAnnotation{
    }
    

    自定义注解

    package com.guanxing.annotation;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    //自定义注解
    public class Test03 {
    
        //注解定义了参数,就要传参,除非有default默认值
    //    @MyAnnotation2(name = "guanxing")
        @MyAnnotation2(name="guanxing")
        public void test(){};
    }
    
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation2{
        //注解的参数:参数类型+名称()
        //参数名为value的话,使用中可以直接赋值
        String name() default "harris";
        int age() default 0;
        int id() default -1;  //如果默认值为-1,代表不存在
    
        String[] schools() default {"华南理工", "中国人大"};
    }
    
  • 相关阅读:
    OpenGL纹理映射总结
    研究生常用网站:
    Oracle 11g,10g数据库软件下载地址
    <转>乔布斯羡慕嫉妒恨的人:Android之父安迪·鲁宾
    VC6里面的中文名字或者注释复制乱码解决
    基于CentOs的Hadoop集群全分布式部署<转>
    centos架设FTP服务器
    centos 卸载 jdk
    ESX的 企业版许可证
    vsftpd的 553 Could not create file
  • 原文地址:https://www.cnblogs.com/straightup/p/14521910.html
Copyright © 2011-2022 走看看