java如何参数注释,Java-如何在单个参数中获取多个注释?

If I have a method like this:

testLink(@LinkLength(min=0, max=5) List link) { ... }

How do I get both @LinkLength and @LinkRange annotation?

解决方案

I'm assuming you want to reflectively access these annotations. Here's an example:

package com.example;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

import java.lang.reflect.AnnotatedParameterizedType;

import java.lang.reflect.AnnotatedType;

import java.lang.reflect.Method;

import java.lang.reflect.Parameter;

import java.util.List;

public class Main {

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.PARAMETER, ElementType.TYPE_USE})

public @interface Foo {

String value();

}

public static void bar(@Foo("parameter") List list) {}

public static void main(String[] args) throws NoSuchMethodException {

Method method = Main.class.getMethod("bar", List.class);

// get annotation from parameter

Parameter parameter = method.getParameters()[0];

System.out.println("PARAMETER ANNOTATION = " + parameter.getAnnotation(Foo.class));

// get annotation from type argument used in parameter

AnnotatedParameterizedType annotatedType =

(AnnotatedParameterizedType) parameter.getAnnotatedType();

AnnotatedType typeArgument = annotatedType.getAnnotatedActualTypeArguments()[0];

System.out.println("TYPE_USE ANNOTATION = " + typeArgument.getAnnotation(Foo.class));

}

}

Which outputs the following:

PARAMETER ANNOTATION = @com.example.Main$Foo(value="parameter")

TYPE_USE ANNOTATION = @com.example.Main$Foo(value="type_use")

Here are the methods used:

The above example makes use of perfect knowledge about the bar method. In other words, I knew there was one parameter, I knew that Parameter#getAnnotatedType() would return AnnotatedParameterizedType, and I knew that the parameterized type had one type argument. This information won't be known ahead-of-time when reflectively scanning an arbitrary class, meaning you'll have to add appropriate checks and only execute certain actions when appropriate. For example:

AnnotatedType type = parameter.getAnnotatedType();

if (type instanceof AnnotatedParameterizedType) {

// do something...

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值