Java基础学习笔记【注解与反射】

反射与注解

1、注解

注解格式:

//以下这些注解称为元注解,即可以添加到注解上的注解
@Target({...ElementType...}) 
@Retention(...RetentionPolicy...)
@Documented - 标记这些注解是否包含在用户文档中。
@Inherited - 标记这个注解是继承于哪个注解类(默认 注解并没有继承于任何子类)
//
@SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
@FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
@Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。
//自定义注解格式:
@interface 注解名称{
//默认参数
String value();
//也可自定义参数,格式如下
类型 类型名称();
类型 类型名称();
... ...

}

其中@Target中的ElementType字段可选值:
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    /** Field declaration (includes enum constants) */
    FIELD,
    /** Method declaration */
    METHOD,
    /** Formal parameter declaration */
    PARAMETER,
    /** Constructor declaration */
    CONSTRUCTOR,
    /** Local variable declaration */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** Package declaration */
    PACKAGE,

@Retention中的字段可选:

    SOURCE, //源码层有效
    CLASS,  //类文件层有效
    RUNTIME //执行层有效 ;绝大部分使用RUNTIME
    //级别:RUNTIME > CLASS > SOURCE

2、反射

//见下面代码

3、代码

有关文件目录
请添加图片描述


package com.reflection;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;

public class test1 {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {


        /**
         * 通过反射创建对象的三种方法
         */
        //1、通过反射创建对象
        Class<?> aClass = Class.forName("com.reflection.User");
        Object user = aClass.newInstance();
        
        
        //2、通过对象创建对象
        User user2 = new User();
        Class bClass = user2.getClass();
        Object o = bClass.newInstance();

        //3、通过反射获得构造器并创建对象;
        //无参构造器
        Constructor<?> ConstructorWithoutField = aClass.getDeclaredConstructor();
        Object ClassBulidByConstructor1 = ConstructorWithoutField.newInstance();
        System.out.println(ClassBulidByConstructor1.toString());
        
        //有参构造器
        Constructor<?> ConstructorWithField = aClass.getDeclaredConstructor(String.class,String.class,Integer.class);
        Object ClassBulidByConstructor2 = ConstructorWithField.newInstance("Robin","Programmer",10086);
        System.out.println(ClassBulidByConstructor2.toString());
        /**
         * 反射操作类获取类的其他信息
         */
        //1、反射实现方法
        Method declaredMethod = aClass.getDeclaredMethod("userIntroduce",null);
        //invoke
        declaredMethod.invoke(ClassBulidByConstructor2);

        //2、反射注解

        //(1)类的注解--反射
        //获取指定注解中的value
        MyAnnotation annotations = aClass.getAnnotation(MyAnnotation.class);
        System.out.println(annotations.value());
        //获取所有的注解
        Annotation[] annotations1 = aClass.getAnnotations();
        for (Annotation i:annotations1) {
            System.out.println(i);
        }

        //(2)方法的注解值--反射
        Method userIntroduce = aClass.getDeclaredMethod("userIntroduce");
        MyAnnotation myAnnotation = userIntroduce.getAnnotation(MyAnnotation.class);
        System.out.println(myAnnotation.value());

        //(3)属性的注解--反射
        Field field = aClass.getDeclaredField("name");
        MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
        System.out.println(annotation.value());

    }
}






User类:

package com.reflection;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@MyAnnotation(value = "I am a Class MyAnnotation")
public class User {

    @MyAnnotation(value = "This is my Field annotation of name.")
    String name;
    @MyAnnotation(value = "This is my Field annotation of filed.")
    String filed;
    @MyAnnotation(value = "This is my Field annotation of id.")
    Integer id;

    public User() {
    }

    @MyAnnotation(value = "This is my annotation.")
    public void userIntroduce(){
        System.out.println("I am"+name+";My major is about"+filed);

    }
    public User(String name, String filed, Integer id) {
        this.name = name;
        this.filed = filed;
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getFiled() {
        return filed;
    }

    public void setFiled(String filed) {
        this.filed = filed;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", filed='" + filed + '\'' +
                ", id=" + id +
                '}';
    }
}
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    String value();
}

请添加图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值