java教程——注解,linux内核编程进阶篇pdf

selfAnnotation annotation = pClass.getAnnotation(selfAnnotation.class);

System.out.println(annotation.type());

}

}

}

@selfAnnotation(type = 2)

class

【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 免费领取

persson{

private int num;

public int getNum(){

return this.num;

}

}

//第三步:添加元注解

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

//第一步:定义注解

@interface selfAnnotation{

//第二步:定义参数

int type() default 1;

}

三、读取方法参数的注解

我们都知道,一个函数的参数可以是多个,而一个参数的注解也可以是多个,所以,我们获取到的 参数的注解是一个二维数组,即第几个参数的第几个注解

package test;

import java.lang.annotation.*;

import java.lang.reflect.Method;

import java.util.Arrays;

public class changeData {

public static void main(String[] args) {

Class pClass = persson.class;

try {

Method method_getNum = pClass.getMethod(“getNum”, int.class);

Annotation[][] parameterAnnotations = method_getNum.getParameterAnnotations();

System.out.println(Arrays.toString(parameterAnnotations[0]));

} catch (NoSuchMethodException e) {

e.printStackTrace();

}

}

}

class persson{

private int num;

public int getNum(@two @one int a){

return this.num;

}

}

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.PARAMETER)

@interface one{

int type() default 1;

}

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.PARAMETER)

@interface two{

int value() default 2;

}

四、使用注解

注解如何使用,完全由程序自己决定。例如,JUnit是一个测试框架,它会自动运行所有标记为@Test的方法。

我们来看一个@Range注解,我们希望用它来定义一个String字段的规则:字段长度满足@Range的参数定义:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.FIELD)

public @interface Range {

int min() default 0;

int max() default 255;

}

在某个JavaBean中,我们可以使用该注解:

public class Person {

@Range(min=1, max=20)

public String name;

@Range(max=10)

public String city;

}

但是,定义了注解,本身对程序逻辑没有任何影响。我们必须自己编写代码来使用注解。这里,我们编写一个Person实例的检查方法,它可以检查Person实例的String字段长度是否满足@Range的定义:

void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {

// 遍历所有Field:

for (Field field : person.getClass().getFields()) {

// 获取Field定义的@Range:

Range range = field.getAnnotation(Range.class);

// 如果@Range存在:

if (range != null) {

// 获取Field的值:

Object value = field.get(person);

// 如果值是String:

if (value instanceof String) {

String s = (String) value;

// 判断值是否满足@Range的min/max:

if (s.length() < range.min() || s.length() > range.max()) {

throw new IllegalArgumentException("Invalid field: " + field.getName());

}

}

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值