• 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("超过最大限度");
                    }
                }       
            }
        }
    }

  • 相关阅读:
    WPF/MVVM 快速开始指南(译)
    Rose2003的安装和破解
    自定义vs代码段
    silverlight中Grid.ColumnDefinitions属性设置错误
    vs绑定和取消绑定项目和解决方案
    firefox浏览器中silverlight无法输入问题
    silverlight中当前上下文中不存在名称“InitializeComponent“错误
    inotify使用代码
    build android toochain on mac (gcc 4.4.3 compile)
    istat 一个不错的widget
  • 原文地址:https://www.cnblogs.com/wyhuang/p/3855158.html
Copyright © 2020-2023  润新知