Java注解与反射系列——反射示例day2-1

news/2024/5/19 5:44:26 标签: java, 开发语言, 注解, 反射

Java注解反射系列——反射示例

反射示例

获取反射对象

java">package example.reflect;



public class demo1 {
    public static void main(String[] args) throws ClassNotFoundException {
        //一个类只有一个class对象
        Class stu = Class.forName("example.reflect.entity.Stu");
        System.out.println(stu);

    }
}

在这里插入图片描述

该方法返回类型为Class类,是Java反射的源头!

源码

java">
    /**
     * Returns the {@code Class} object associated with the class or
     * interface with the given string name.  Invoking this method is
     * equivalent to:
     *
     * <blockquote>
     *  {@code Class.forName(className, true, currentLoader)}
     * </blockquote>
     *
     * where {@code currentLoader} denotes the defining class loader of
     * the current class.
     *
     * <p> For example, the following code fragment returns the
     * runtime {@code Class} descriptor for the class named
     * {@code java.lang.Thread}:
     *
     * <blockquote>
     *   {@code Class t = Class.forName("java.lang.Thread")}
     * </blockquote>
     * <p>
     * A call to {@code forName("X")} causes the class named
     * {@code X} to be initialized.
     *
     * @param      className   the fully qualified name of the desired class.
     * @return     the {@code Class} object for the class with the
     *             specified name.
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located
     */
    @CallerSensitive
    public static Class<?> forName(String className)
                throws ClassNotFoundException {
        Class<?> caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }

通过反射机制动态创建对象

首先明确一点:jdk8以后已不推荐直接使用newInstance来构建对象
在这里插入图片描述
以此代替(调用的是无参构造)

java">        Class<Stu> stuClass = Stu.class;
        Stu stu1 = stuClass.getDeclaredConstructor().newInstance();

完整代码

java">package example.reflect;

import example.reflect.entity.Stu;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClass {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<Stu> stuClass = Stu.class;
        //无参构造
        Stu stu1 = stuClass.getDeclaredConstructor().newInstance();
        System.out.println(stu1);

    }
}

在这里插入图片描述

通过反射调用方法

java">package example.reflect;

import example.reflect.entity.Stu;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClass {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<Stu> stuClass = Stu.class;
        //无参构造
        Stu stu1 = stuClass.getDeclaredConstructor().newInstance();
//        System.out.println(stu1);

        //通过反射调用普通方法
        Method setAge = stuClass.getDeclaredMethod("setAge", int.class);
        //使用invoke方法进行激活
        setAge.invoke(stu1,18);
        System.out.println(stu1.getAge());
    }
}

在这里插入图片描述

通过反射设置属性

java">package example.reflect;

import example.reflect.entity.Stu;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClass {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<Stu> stuClass = Stu.class;
        //无参构造
        Stu stu1 = stuClass.getDeclaredConstructor().newInstance();
//        System.out.println(stu1);


        //通过反射使用属性
        Field name = stuClass.getDeclaredField("name");
        //关闭安全检测
        name.setAccessible(true);
        name.set(stu1,"张三");
        System.out.println(stu1.getName());

    }
}

在这里插入图片描述

通过反射获取泛型

getGenericReturnType方法用于获取返回值类型

java">package example.reflect;

import example.reflect.entity.Stu;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class GetExtendType {
    public void test(Map<String, Stu> map, List<Stu> list){
        map.forEach((x,y)->{
            System.out.println(x+y);
        });
    }

    public static void main(String[] args) throws NoSuchMethodException {
        //通过反射获取泛型
        Method test = GetExtendType.class.getMethod("test", Map.class, List.class);
        //获取方法参数类型
        Type[] genericParameterTypes = test.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
//            System.out.println(genericParameterType);
            //判断是否属于参数化类型
            if(genericParameterType instanceof ParameterizedType){
                //获取真实的参数
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {

                    System.out.println(actualTypeArgument);
                }
            }
        }
    }
}

在这里插入图片描述

反射操作注解(重要)

java">package example.reflect;

import example.annotation.AnnoField;
import example.annotation.MyAnno;
import example.reflect.entity.Stu;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class GetAnnotation {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<Stu> stuClass = Stu.class;
//        Stu stu = stuClass.getDeclaredConstructor().newInstance();

        //通过反射获取类上的注解
        Annotation[] annotations = stuClass.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        //获取注解中的值
        MyAnno annotation = stuClass.getAnnotation(MyAnno.class);
        String value = annotation.value();
        System.out.println(value);

        //获取属性上的注解
        Field age = stuClass.getDeclaredField("age");
        AnnoField annotation1 = age.getAnnotation(AnnoField.class);
        System.out.println(annotation1.col());
        System.out.println(annotation1.type());
        
    }
}

在这里插入图片描述


http://www.niftyadmin.cn/n/1717345.html

相关文章

Java注解与反射系列——注解与反射实例day2-2

Java注解与反射系列——注解与反射实例实例CheckMethod注解Stu类测试实例 用于获取所有带有注解的方法的方法名并记录日到txt中 CheckMethod注解 package example.annotation;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java…

linux服务器管理——高可用电商项目系统部署方案

linux服务器管理——高可用电商项目系统部署方案高可用电商项目系统部署方案报告前言[摘 要][关键词]环境拓扑图完整拓扑图准备工作必要安装和操作克隆搭建LVS的DR模式简单拓扑配置IProuter查看网卡的uuid以及mac地址配置静态IP测试连通router启动路由转发查看路由表lvs1lvs2RS…

Java接口详解

Java接口什么是Java接口接口特性接口与类的区别接口特性抽象类和接口的区别如何定义接口接口的进化jdk7jdk8jdk9接口实现接口示例抽象方法1.创建接口2.书写要实现的方法3.构建实现类4.实现类5.实现方法静态常量默认方法覆盖实现静态方法私有方法普通私有方法静态私有方法接口的…

Java8时间与日期API(别再使用Date和Calendar了)

Java8时间与日期APIAPI设计原因时间日期常用类概述创建方法&#xff08;now&#xff09;生成自定义的日期时间对象&#xff08;of&#xff09;为LocalDateTime添加时区信息ZoneId类获取系统时区获取其他时区的时间关于Month枚举根据现有时间进行时间推断&#xff08;plus&#…

SpringSecurity系列——概述day1-1

SpringSecurity系列——概述简介什么是授权什么是认证quickstart1.创建项目选择依赖SpringSecurity依赖2.Controller测试3.访问localhost8080/demo用户名和密码4.登录5.退出登录简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安…

SpringSecurity系列——JWT(jjwt)day1-2

SpringSecurity系列——JWTday1-2简介官网地址Session对比JWTsession问题JWTJWT的优点JWT的结构HeaderPayloadSignatureJJWT地址JJWT基础使用和介绍导入依赖quickstart代码解释设置使用加密算法构建jwt设置payload中包含的用户信息设置加密算法压缩生成token令牌错误一&#xf…

SpringSecurity系列——简单自定义登录流程day1-3

SpringSecurity系列——简单自定义登录流程SpringSecurity认证前后端分离的登录校验流程前后端分离请求响应流程SpringSecurity完整流程如何查看过滤器1.启动类中添加逻辑进行debug2.打开评估输入表达式修改流程登录校验自定义登录流程1.导入依赖2.编写yaml3.编写entity&#x…

SpringSecurity系列——简单自定义登录流程问题解析day1-4

简单自定义登录流程问题解析对day1-3中简单自定义登录流程梳理问题为什么需要在密码前加{noop}&#xff08;密码加密存储&#xff09;密码加密简介散列加密概述散列加密原理Spring Security中的密码处理方案如何使用BCryptPasswordEncoder&#xff1f;简单使用具体如何使用&…