JAVA 自定义注解及参数获取

本文介绍如何在Java中自定义注解,包括注解的定义、使用和获取注解参数的方法,并通过实例展示其在实际开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.java.annotation;

import java.lang.annotation.*;

/**
 * Created by lw on 14-5-30.
 * 自定义注解
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo {
    public String Value() default "暂无说明";
}
/*
四个定义注解时候的限定数据

@Target(ElementType.TYPE)           :接口、类、枚举、注解
@Target(ElementType.FIELD)          :字段、枚举的常量
@Target(ElementType.METHOD)         :方法
@Target(ElementType.PARAMETER)      :方法参数
@Target(ElementType.CONSTRUCTOR)    :构造函数
@Target(ElementType.LOCAL_VARIABLE) :局部变量
@Target(ElementType.ANNOTATION_TYPE):注解
@Target(ElementType.PACKAGE)        :包

@Retention(RetentionPolicy.SOURCE)  :在源文件中有效(即源文件保留)
@Retention(RetentionPolicy.CLASS)   :在class文件中有效(即class保留)
@Retention(RetentionPolicy.RUNTIME) :在运行时有效(即运行时保留)

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

@Document:说明该注解将被包含在javadoc中
*/


package com.java.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Created by lw on 14-5-30.
 */
public class Test {


    /**
     * 获取注解参数
     *
     * @param annotationClass 注解类
     * @param annotationField 注解类字段名称
     * @param aClass          使用注解的class名称
     * @param methodName      使用注解的方法名称
     * @throws Exception
     */
    public static void getAnnotationPar(Class annotationClass, String annotationField, Class aClass, String methodName) throws Exception {

        Method aClassMethod = aClass.getMethod(methodName);
        Annotation annotation = aClassMethod.getAnnotation(annotationClass);
        Method method = annotation.getClass().getDeclaredMethod(annotationField);
        System.out.println(method.invoke(annotation));
    }

    public static void main(String[] args) throws Exception {
        Test.getAnnotationPar(MethodInfo.class, "Value", Test2Annotation.class, "testMyAnnotation");
    }
}

class Test2Annotation {
    @MethodInfo(Value = "自定义的注解@MethodInfo")
    public void testMyAnnotation() {

    }
}

源码:https://github.com/xiaohulu/util_xiaohulu/tree/master/src/com/java/annotation

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值