java教程——注解(二)

知识背景

在 java教程——注解 这一节中我们提到过这么一句话:“这是Java代码读取该注解实现的功能,JVM并不会识别该注解“。所以,下面的内容就是教大家如何读取并识别自己写的注解。

我们都知道 注解是 分为三类的,根据运行时机(@Retention)可以分为:

  • SOURCE类型的注解在编译期就被丢掉了;
  • CLASS类型的注解仅保存在class文件中,它们不会被加载进JVM;
  • RUNTIME类型的注解会被加载进JVM,并且在运行期可以被程序读取。

我们反复强调:RUNTIME类型的注解不但要使用,还经常需要编写。因此,我们只讨论如何读取RUNTIME类型的注解。

因为注解定义后也是一种class,所有的注解都继承自java.lang.annotation.Annotation,因此,读取注解,需要使用反射API

一、判断某个注解是否存在于ClassFieldMethodConstructor

Class.isAnnotationPresent(Class)
Field.isAnnotationPresent(Class)
Method.isAnnotationPresent(Class)
Constructor.isAnnotationPresent(Class)
package test;

import java.lang.annotation.*;

public class changeData {

    public static void main(String[] args) {
        Class<persson> pClass = persson.class;
        System.out.println(pClass.isAnnotationPresent(selfAnnotation.class));
    }
}

@selfAnnotation
class persson{
    private int num;
    public int getNum(){
        return this.num;
    }
}

//第三步:添加元注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
//第一步:定义注解
@interface selfAnnotation{
    //第二步:定义参数
    int type() default 1;
}

 

二、使用反射API读取Annotation:

Class.getAnnotation(Class)
Field.getAnnotation(Class)
Method.getAnnotation(Class)
Constructor.getAnnotation(Class)
package test;

import java.lang.annotation.*;

public class changeData {

    public static void main(String[] args) {
        Class<persson> pClass = persson.class;
        if(pClass.isAnnotationPresent(selfAnnotation.class)){
            selfAnnotation annotation = pClass.getAnnotation(selfAnnotation.class);
            System.out.println(annotation.type());
        }
    }
}

@selfAnnotation(type = 2)
class 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<persson> 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());
                }
            }
        }
    }
}

这样一来,我们通过@Range注解,配合check()方法,就可以完成Person实例的检查。注意检查逻辑完全是我们自己编写的,JVM不会自动给注解添加任何额外的逻辑。

这里面还涉及到了反射的知识点,大家可以查看这几篇文章 java教程——反射(一)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring AOP是Spring框架中的一个重要模块,它提供了面向切面编程(AOP)的支持。AOP是一种编程思想,它可以在不改变原有代码的情况下,通过在程序运行时动态地将代码“织入”到现有代码中,从而实现对原有代码的增强。 Spring AOP提供了基于注解的AOP实现,使得开发者可以通过注解的方式来定义切面、切点和通知等相关内容,从而简化了AOP的使用。 下面是一个基于注解的AOP实现的例子: 1. 定义切面类 ```java @Aspect @Component public class LogAspect { @Pointcut("@annotation(Log)") public void logPointcut() {} @Before("logPointcut()") public void beforeLog(JoinPoint joinPoint) { // 前置通知 System.out.println("执行方法:" + joinPoint.getSignature().getName()); } @AfterReturning("logPointcut()") public void afterLog(JoinPoint joinPoint) { // 后置通知 System.out.println("方法执行完成:" + joinPoint.getSignature().getName()); } @AfterThrowing(pointcut = "logPointcut()", throwing = "ex") public void afterThrowingLog(JoinPoint joinPoint, Exception ex) { // 异常通知 System.out.println("方法执行异常:" + joinPoint.getSignature().getName() + ",异常信息:" + ex.getMessage()); } } ``` 2. 定义业务逻辑类 ```java @Service public class UserService { @Log public void addUser(User user) { // 添加用户 System.out.println("添加用户:" + user.getName()); } @Log public void deleteUser(String userId) { // 删除用户 System.out.println("删除用户:" + userId); throw new RuntimeException("删除用户异常"); } } ``` 3. 在配置文件中开启AOP ```xml <aop:aspectj-autoproxy/> <context:component-scan base-package="com.example"/> ``` 在这个例子中,我们定义了一个切面类LogAspect,其中通过@Aspect注解定义了一个切面,通过@Pointcut注解定义了一个切点,通过@Before、@AfterReturning和@AfterThrowing注解分别定义了前置通知、后置通知和异常通知。 在业务逻辑类中,我们通过@Log注解标注了需要增强的方法。 最后,在配置文件中,我们通过<aop:aspectj-autoproxy/>开启了AOP功能,并通过<context:component-scan>扫描了指定包下的所有组件。 这样,当我们调用UserService中的方法时,就会触发LogAspect中定义的通知,从而实现对原有代码的增强。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

super码王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值