首页 > 代码库 > Java中注解

Java中注解

Java中Annotation其实就是代码里的特殊标记,它可以用来代替配置文件

 

自定义注解的步骤:

1、编写注解类:

使用@interface 定义

package cn.cqu.huang;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
    double max();
}

2、在一个类 应用注解类,并通过反射技术获取注解中的信息

package cn.cqu.huang;

@MyAnnotation(max = 5000)
public class BankAccount {
    private double amount;
   
    public BankAccount(double amount) {
        this.amount = amount;
    }
   
    public void transfer(double money){
        if(money>amount){
            System.out.println("您的余额不足");
        }else{
            Class c = BankAccount.class;
            boolean isexist = c.isAnnotationPresent(MyAnnotation.class);
            if(isexist){
                MyAnnotation myannotation = (MyAnnotation) c.getAnnotation(MyAnnotation.class);
                double max = myannotation.max();
                if(money<max){
                    System.out.println("转出金额为:"+money);
                    amount-=money;
                }else{
                    throw new RuntimeException("超过最大限度");
                }
            }       
        }
    }
}