Java注解

目录

一、Java注解分类

二、实现自定义注解


一、Java注解分类

java注解分为:标准注解、元注解、自定义注解3类。

1.标准注解

        标准注解是java自带的注解,包含如下:

@Override:标记覆写父类的函数,若父类无该方法,会编译警告(不影响函数运行结果,java默认所有函数都是virtual,覆写函数默认支持多态)


@Deprecated:标记过时方法,使用该方法会有编译警告


@SuppressWarnings:用于关闭对类、方法、成员编译时产生的特定警告

2.元注解

        元注解是注解的注解,包含如下:

@Retention:用来定义该注解在哪一个级别可用,在源代码中(SOURCE)、类文件中(CLASS)或者运行时(RUNTIME)

  1. SOURCE:表示该注解仅在源代码级别保留,编译后的字节码中不保留。这意味着该注解在运行时不可见,对于运行时的程序没有任何影响。这种类型的注解一般用于提供额外的编译时信息,用于辅助开发工具或静态代码分析工具。(如:@Override、@SuppressWarnings)

  2. CLASS:表示该注解在编译后的字节码中保留,但在运行时不可用。这意味着虚拟机加载类时无法访问该注解。它可以用于一些框架或工具在编译时进行一些处理,但在运行时不需要访问注解。

  3. RUNTIME:表示该注解在编译后的字节码中保留,并可以在运行时通过反射机制访问。这种类型的注解在运行时是可见的,并且可以通过反射机制来读取注解的信息,通常用于运行时的框架或系统。(如:@Deprecated)

@Documented:生成文档信息的时候保留注解,对类作辅助说明

@Target:用于描述注解的使用范围

@Inherited:说明子类可以继承父类中的该注解

@Repeatable:表示注解可以重复使用

3.自定义注解

        开发人员自定义的注解

二、实现自定义注解

示例如下:

package org.example;

import java.lang.annotation.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@interface helloAnnotation {
    String value();
}

class HelloAnnotationClient {
    @helloAnnotation(value="Simple custom Annotation example")
    public void sayHello(){
        System.out.println("Inside sayHello method..");
    }
}


public class App
{
    public static void main( String[] args ) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {

        HelloAnnotationClient helloAnnotationClient=new HelloAnnotationClient();
        Method method=helloAnnotationClient.getClass().getMethod("sayHello");
        if(method.isAnnotationPresent(helloAnnotation.class)){
            helloAnnotation helloAnnotation=method.getAnnotation(helloAnnotation.class);
            //获取方法上的注解并输出注解的值
            System.out.println("Value : "+helloAnnotation.value());
            //调用sayHello函数
            method.invoke(helloAnnotationClient);
        }
    }
}

你可能感兴趣的:(java,java,开发语言)