简单介绍java反射机制中Annotation(注解)与Method的程序示例

首先,这篇文章是针对对java有一定基础的伙伴,尽请见谅。今天,小芳给大家写了一个简单的程序,关于注解(Annotation)与反射机制。
注解的详细介绍大家可以参考:https://www.cnblogs.com/xdp-gacl/p/3622275.html。这篇文章里面有非常详细的介绍。
好了,接下来给大家展示我写的简单的程序:
先看一下我写的注解:

package com.mec.about_reflection.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//Retention与Target都是元注解(注解的注解),前者表明这个注解的作用范围,它有三种取值:RetentionPolicy.SOURCE、RetentionPolicy.CLASS、RetentionPolicy.RUNTIME分别对应:Java源文件(.java文件)---->.class文件---->内存中的字节码,后者表明这个注解的作用范围(即作用于包、类、字段、方法)
@Retention(RetentionPolicy.RUNTIME)  //运行时检查
@Target(value= {ElementType.METHOD}) //作用于方法上
public @interface Reflection {
    //定义两个成员,未赋初值,这要求在用到这个注解时要给这两个值赋初值
    int max(); 
    int min();
}

这是一个简单的类:

package com.mec.about_reflection;
import com.mec.about_reflection.annotation.Reflection;
public class PersonClass {
    public  String  name;
    private  Integer  age;
    private  String  sex;

    public PersonClass() {
    }

    public PersonClass(String name, Integer age, String sex) {
        super();
        this.setName(name);
        this.setAge(age);
        this.setSex(sex);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }
    //这里是对上面定义的注解的使用,使用时给它的两个成员赋初值,若不赋初值则显示有错误。
    @Reflection(min = 12,max = 109)
    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "PersonClass [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }
}

接下来,我们用反射机制测试一下这个注解:

package com.mec.about_reflection.annotation.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.mec.about_reflection.annotation.Reflection;

public class TestAnnotation {
    public static void main(String[] args) {
        String className = "com.mec.about_reflection.PersonClass";
        Integer val = 40;
        try {
            //首先,通过反射机制得到这个类,通过反射机制得到一个类有三种方法:1.通过类名得到;2.通过完整的类名得到;3.通过对象名 Object object = new PersonClass()。这里用到的是全类名。
            Class classOne = Class.forName(className);
            //创建一个这个类的实例
            Object object = classOne.newInstance();
            System.out.println("获取的类");
            //获取这个类的特定的方法
            Method method = classOne.getDeclaredMethod("setAge", Integer.class);
            //得到这个方法之后,再获取这个方法的注解
            Annotation annotation = method.getAnnotation(Reflection.class);
            System.out.println(annotation);
            //判断这个注解是否为空或者,这个方法的注解是不是我们所写的这个注解
            if(annotation != null && annotation instanceof Reflection) {
                //如果上述条件成立,则对这个注解进行类型强转
                Reflection reflection = (Reflection) annotation;
                //判断这个范围是不是在我这个注解的范围之内
                if(val > reflection.max() || val < reflection.min()) {
                    //如果不在注解的范围之内则给出提示
                    throw new RuntimeException("数值超出范围!");
                }
            }
        //执行这个方法
        method.invoke(object, val);
        输出这个对象,这里默认输出的是它的toString()方法
        System.out.println("object:" + object);


        } catch (ClassNotFoundException | InstantiationException 
                | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

输出结果如下:

获取的类
@com.mec.about_reflection.annotation.Reflection(min=12, max=109)
object:PersonClass [name=null, age=40, sex=null]

好了,程序说完了。这个程序非常浅显,虽然我已经学了java快半年了,但是还是很差。有写的不对的地方请大家多多提出意见。不胜感激!!
路漫漫其修远兮,吾将上下而求索

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值