Java反射、自定义注解Demo

news2024/10/5 15:44:44

本文主要尝试使用反射、自定义注解,实现简单的Demo,所有代码均可直接复制使用。(反射和注解是Java框架不可或缺的一部分,我们应该熟练掌握这部分知识!)

本文的代码结构如下:

代码如下:

类People

包含公有字段、私有字段、公有方法、私有方法

package com.cocoa.dao;
public class People {
    private String county;
    private String peoplePrivateFiled1;
    private int peoplePrivateFiled2;
    public String peoplePublicFiled1;
    public String peoplePublicFiled2;

    public People() {}

    public People(String county, String peoplePrivateFiled1, int peoplePrivateFiled2, String peoplePublicFiled1, String peoplePublicFiled2) {
        this.county = county;
        this.peoplePrivateFiled1 = peoplePrivateFiled1;
        this.peoplePrivateFiled2 = peoplePrivateFiled2;
        this.peoplePublicFiled1 = peoplePublicFiled1;
        this.peoplePublicFiled2 = peoplePublicFiled2;
    }

    private void peoplePrivate(){
        System.out.println("people private method -- print");
    }

    public void peoplePublic(){
        System.out.println("people public method -- print");
    }
}

类Student

包含公有字段、私有字段、公有方法、私有方法

package com.cocoa.dao;

import com.cocoa.myAnnotation.PrivateMethod;
import com.cocoa.myAnnotation.PublicMethod;

public class Student extends People implements Sport{
    public int studentPublicField1;
    public String studentPublicField2;
    private int studentPrivateField1;
    private String studentPrivateField2;

    public Student(){}

    public Student( int studentPublicField1, String studentPublicField2, int studentPrivateField1, String studentPrivateField2) {
        this.studentPublicField1 = studentPublicField1;
        this.studentPublicField2 = studentPublicField2;
        this.studentPrivateField1 = studentPrivateField1;
        this.studentPrivateField2 = studentPrivateField2;
    }

    private void studentPrivateMethod1(){
        System.out.println("student private method1 -- print");
    }
    @PrivateMethod({"123", "123"})
    private void studentPrivateMethod2(int age){
        System.out.print(age + " = ");
        System.out.println("student private method2 -- print");
    }
    @PublicMethod
    public void studentPublicMethod(){
        System.out.println("student public method -- print");
    }

    public static void studentStaticPublicMethod(int age){
        System.out.println("student studentStaticPublicMethod -- print");
    }

    public People setStudentPublicMethodReturn(){
        return new People();
    }

    @Override
    public void playBadminton() {
        System.out.println("student playBadminton");
    }

    @Override
    public void playfootball() {
        System.out.println("student playfootball");
    }
}

接口Sport

package com.cocoa.dao;

public interface Sport {
    public void playBadminton();
    public void playfootball();
}

自定义注解@PrivateMethod

package com.cocoa.myAnnotation;

import java.lang.annotation.*;

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PrivateMethod {

    String[] value() default "";
}

自定义注解@PublicMethod

package com.cocoa.myAnnotation;

import java.lang.annotation.*;

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PublicMethod {

    String value() default "";
}

 类ReflectDemo1

执行方法,获取入参数量、入参类型

package com.cocoa.reflectDemo;

import com.cocoa.dao.Student;
import java.lang.reflect.*;

/**
 * 执行 方法,拿到方法上的注解,执行方法,获取入参数量、入参类型
 */
public class ReflectDemo1 {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Student student = new Student();
        Class<?> aClass = student.getClass();
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods){
            String name = method.getName();
            System.out.println("method的name  = " + name);
            // 拿到方法的入参数量
            int parameterCount = method.getParameterCount();
            System.out.println("method的入参数量 = " + parameterCount);
            if (parameterCount == 0){
                // 将方法的访问权限设为公有,绕过方法的访问控制
                method.setAccessible(true);
                // 执行方法
                method.invoke(student);
            }else if (parameterCount == 1){
                // 将方法的访问权限设为公有,绕过方法的访问控制
                method.setAccessible(true);
                // 执行方法
                method.invoke(student, 18);
            }
            // 拿到方法的修饰符
            int modifiers = method.getModifiers();
            System.out.println(Modifier.toString(modifiers));
            Parameter[] parameters = method.getParameters();
            for (Parameter parameter : parameters){
                Type parameterizedType = parameter.getParameterizedType();
                System.out.println("method入参的基本信息 = " + parameter + ",修饰符 = " + parameterizedType.getTypeName());
            }

            System.out.println("---------------------------");
        }
    }
}

类ReflectDemo2

拿到字段,包括修饰符,修改字段

package com.cocoa.reflectDemo;

import com.cocoa.dao.Student;
import java.lang.reflect.*;

/**
 * 拿到字段 的相关内容,包括修饰符、修改字段
 */
public class ReflectDemo2 {
    public static void main(String[] args) throws IllegalAccessException {
        Class<?> aClass = Student.class;
        // 拿到本类 和 父类的所有 public字段
        Field[] fields = aClass.getFields();
        for (Field field : fields){
            System.out.println(field);
        }
        System.out.println("---------------------------");
        // 拿到本类所有字段,包含public 和 private
        Field[] declaredFields = aClass.getDeclaredFields();
        Student student = new Student();
        for (Field field : declaredFields){
            // 输出字段的所有信息
            System.out.println(field);
            // 输出字段的名字
            String name = field.getName();
            System.out.println(name);
            // 拿到字段的修饰符
            int modifiers = field.getModifiers();
            System.out.println(Modifier.toString(modifiers));
            // 拿到字段的类型
            Type type = field.getType();
            System.out.println(type.getTypeName());
            // 给字段赋值
            field.setAccessible(true);
            if (type.equals(int.class) ){
                field.set(student, 11);
            }else {
                field.set(student, "test");
            }
            System.out.println("---------------------------");
        }
        System.out.println(student.studentPublicField1);
        System.out.println(student.studentPublicField2);

    }
}

类ReflectDemo3

执行类的static方法

package com.cocoa.reflectDemo;


import com.cocoa.dao.Student;

import java.lang.reflect.*;

/**
 * 反射 执行 类的static方法
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Class<?> aClass = Student.class;
        // 执行Student类的static方法
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods){
            int modifiers = method.getModifiers();
            if (Modifier.isStatic(modifiers)){
                System.out.println(method.getName());
                method.invoke(null, 19);
            }
        }

    }
}

类ReflectDemo4

拿到方法的返回值,并判断返回值的类型等

package com.cocoa.reflectDemo;


import com.cocoa.dao.People;
import com.cocoa.dao.Student;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射 拿到 方法的返回值
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Class<?> aClass = Student.class;
        // 执行Student类的static方法
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods){
            Class<?> returnType = method.getReturnType();
            if (returnType.equals(void.class)){
                System.out.println(method.getName() + " 没有返回值");
            }else {
                System.out.print(method.getName() + " 有返回值,为: ");
                System.out.println(returnType);

                // 执行 有返回值的 方法
                Student student = new Student();
                Object invoke = method.invoke(student);
                if (invoke instanceof People){
                    People p = (People) invoke;
                    p.peoplePublic();
                }
            }
        }
    }
}

类ReflectDemo5

测试自定义注解


package com.cocoa.reflectDemo;

import com.cocoa.dao.Student;
import com.cocoa.myAnnotation.PrivateMethod;
import com.cocoa.myAnnotation.PublicMethod;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 使用自定义注解
 */
public class ReflectDemo5 {
    public static void main(String[] args){
        Class<?> aClass = Student.class;

        // 执行Student类的static方法
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods){
            // 获取方法上的自定义注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations){
                // 用于判断方法上的注解是PublicMethod吗
                System.out.println(annotation.annotationType().equals(PublicMethod.class));
                // 拿到注解的缩写类名
                System.out.println("方法" + method.getName() + "注解为:" + annotation.annotationType().getSimpleName());

                System.out.println("输出注解@PrivateMethod的value: ");
                if (annotation.annotationType().equals(PrivateMethod.class)){
                    PrivateMethod annotation2 = (PrivateMethod) annotation;
                    System.out.print("注解的value = { ");
                    for (String s : annotation2.value()){
                        System.out.print(s + " ");
                    }
                    System.out.println("}");
                }
            }
        }
    }
}

类ReflectDemo6

获取类的父类的方法


package com.cocoa.reflectDemo;

import com.cocoa.dao.Student;
import com.cocoa.myAnnotation.PrivateMethod;
import com.cocoa.myAnnotation.PublicMethod;

import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;

/**
 * 获取父类的所有方法
 */
public class ReflectDemo6 {
    public static void main(String[] args){
        Class<?> aClass = Student.class;
        Class<?> superclass = aClass.getSuperclass();// 拿到父类

        Method[] declaredMethods = superclass.getDeclaredMethods();
        for (Method method : declaredMethods){
            System.out.println(method.getName());
        }

    }
}

类ReflectDemo7

获取类的接口信息,获取类上的注解


package com.cocoa.reflectDemo;

import com.cocoa.dao.Student;

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

/**
 * 获取 类的接口信息
 */
public class ReflectDemo7 {
    public static void main(String[] args){
        Class<?> aClass = Student.class;
        // 获取类的接口
        Class<?>[] interfaces = aClass.getInterfaces();
        for (Class<?> interface1 : interfaces){
            System.out.println(interface1.getSimpleName());
            Method[] declaredMethods = interface1.getDeclaredMethods();
            System.out.println("--------------------");
            for (Method method : declaredMethods){
                System.out.println(method.getName());
            }
        }
        // 获取类的注解信息
        Annotation[] annotations = aClass.getAnnotations();
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2190112.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Linux】详解Linux下的工具(内含yum指令和vim指令)

文章目录 前言1. Linux下软件安装的方式2. yum2.1 软件下载的小知识2.2 在自己的Linux系统下验证yum源的存在2.3 利用yum指令下载软件2.4 拓展yum源&#xff08;针对于虚拟机用户&#xff09; 3. vim编辑器3.1 vim是什么&#xff1f;3.2 如何打开vim3.2 vim各模式下的讲解3.2.1…

高级图片编辑器Photopea

什么是 Photopea &#xff1f; Photopea 是一款免费的在线工具&#xff0c;用于编辑光栅和矢量图形&#xff0c;支持PSD、AI 和 Sketch文件。 功能上&#xff0c;Photopea 和 老苏之前介绍的 miniPaint 比较像 文章传送门&#xff1a;在线图片编辑器miniPaint 支持的格式 复杂…

创建django项目,编译类型选择Custom environment后,却没有manage.py文件,无法启动项目?

选择 Custom environment 创建后&#xff0c;启动项目却发现没有manage.py文件 解决办法&#xff1a; 1、 首先查看项目中是否安装了django&#xff0c;没有则安装 2 、创建项目&#xff08;这里的myproject则表示项目名&#xff09; django-admin startproject myproject …

C语言 | Leetcode C语言题解之第454题四数相加II

题目&#xff1a; 题解&#xff1a; struct hashTable {int key;int val;UT_hash_handle hh; };int fourSumCount(int* A, int ASize, int* B, int BSize, int* C, int CSize, int* D, int DSize) {struct hashTable* hashtable NULL;for (int i 0; i < ASize; i) {for (…

外包功能测试干了4年,技术退步太明显了。。。。。​

先说一下自己的情况&#xff0c;本科生&#xff0c;18年通过校招进入武汉某软件公司&#xff0c;干了差不多4年的功能测试&#xff0c;今年中秋&#xff0c;感觉自己不能够在这样下去了&#xff0c;长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测…

Day01-postgresql数据库基础入门培训

Day01-postgresql数据库基础入门培训 1、PostgresQL数据库简介2、PostgreSQL行业生态应用3、PostgreSQL版本发展与特性4、PostgreSQL体系结构介绍5、PostgreSQL与MySQL的区别6、PostgreSQL与Oracle、MySQL的对比 1、PostgresQL数据库简介 PostgreSQL【简称&#xff1a;PG】是加…

搭建shopify本地开发环境

虽然shopify提供了在线编辑器的功能&#xff0c;但是远不及本地编辑器方便高效&#xff0c;这篇文章主要介绍如何在本地搭建shopify开发环境&#xff1a; 1、安装nodejs 18.2 2、安装git 3、安装shopify cli ,使用指令: npm install -g shopify/clilatest 4、安装ruby 5、…

软件设计师——数据结构

本博文所有内容来自于B站up主zst_2001 目录 时间复杂度 常规数据结构 链表 栈与队列 ​编辑 串 数组 树 卡特兰数&#xff1a; 平衡二叉树 哈夫曼 图 AOV 排序 顺序 折半 哈希 时间复杂度 常规数据结构 链表 栈与队列 串 找i位置前面的字符串&#xff0c…

JS | JavaScript中document.write()有哪些用法?

document.write()是 JavaScript 中用于向文档中插入内容的方法。它可以在文档加载过程中或在脚本执行时动态地将任意内容写入到 HTML 文档中。 document.write() 是 JavaScript 中的一个方法&#xff0c;用于在 HTML 文档中动态生成内容。 这个方法可以在网页加载过程中动态地…

Python 工具库每日推荐 【Pandas】

文章目录 引言Python数据处理库的重要性今日推荐:Pandas工具库主要功能:使用场景:安装与配置快速上手示例代码代码解释实际应用案例案例:销售数据分析案例分析高级特性数据合并和连接时间序列处理数据透视表扩展阅读与资源优缺点分析优点:缺点:总结【 已更新完 TypeScrip…

重学SpringBoot3-集成Redis(一)

更多SpringBoot3内容请关注我的专栏&#xff1a;《SpringBoot3》 期待您的点赞&#x1f44d;收藏⭐评论✍ 重学SpringBoot3-集成Redis&#xff08;一&#xff09; 1. 项目初始化2. 配置 Redis3. 配置 Redis 序列化4. 操作 Redis 工具类5. 编写 REST 控制器6. 测试 API7. 总结 随…

【复习】html最重要的表单和上传标签

文章目录 imgforminput img <img src"https://tse1-mm.cn.bing.net/th/id/OIP-C._XVJ53-pN6sDMXp8W19F4AAAAA?rs1&pidImgDetMain"alt"二次元"height"350px"width"200px"/>常用 没啥说的&#xff0c;一般操作css多一些 for…

Nacos理论知识+应用案例+高级特性剖析

一、理论知识 Nacos功能 Nacos常用于注册中心、配置中心 Nacos关键特性 1、服务发现和服务健康监测 nacos作为服务注册中心可用于服务发现,并支持传输层&#xff08;TCP&#xff09;和应用层(HTTP&#xff09;的健康检查&#xff0c;并提供了agent上报和nacos server端主动…

数据结构——List接口

文章目录 一、什么是List&#xff1f;二、常见接口介绍三、List的使用总结 一、什么是List&#xff1f; 在集合框架中&#xff0c;List是一个接口&#xff0c;通过其源码&#xff0c;我们可以清楚看到其继承了Collection。 Collection 也是一个接口&#xff0c;该接口中规范了后…

启动redis

1. 进入root的状态&#xff0c;sudo -i 2. 通过sudo find /etc/redis/ -name "redis.conf"找到redis.conf的路径 3. 切换到/etc/redis目录下&#xff0c;开启redis服务 4. ps aux | grep redis命令查看按当前redis进程&#xff0c;发现已经服务已经开启 5.关闭服务…

如何使用WPS软件里的AI工具?

在wps文档中随机位置&#xff0c;按两下键盘上的【CTRL】键&#xff0c;唤醒AI工具 然后&#xff0c;输入想要的问题后&#xff0c;按下【回车】&#xff0c;就会生成答案在文档中 如果答案是自己喜欢的&#xff0c; 则选择【保留】&#xff0c;即可保存在文档中 如果答案不是…

Arthas(阿尔萨斯)

Arthas Arthas可以为你做什么&#xff1f; 安装下载 //Linux环境下 wget https://alibaba.github.io/arthas/arthas-boot.jar //Windows环境下可以直接去官网下载压缩包 https://arthas.aliyun.com/doc/download.html//启动命令 java -jar arthas-boot.jar 启动阿尔萨斯&#…

使用Conda管理python环境的指南

1. 准备 .yml 文件 确保你有一个定义了 Conda 环境的 .yml 文件。这个文件通常包括环境的依赖和配置设置。文件内容可能如下所示&#xff1a; name: myenv channels:- defaults dependencies:- python3.8- numpy- pandas- scipy- pip- pip:- torch- torchvision- torchaudio2…

【我的 PWN 学习手札】tcache stash unlink

目录 前言 一、相关源码 二、过程图示 1. Unlink 过程 2. Tcache stash unlink 过程 三、测试与模板 1. 流程实操 2. 相关代码 前言 tcache stashing unlink atttack 主要利用的是 calloc 函数会绕过 tcache 从smallbin 里取出 chunk 的特性。并且 smallbin 分配后&…

IP 数据包分包组包

为什么要分包 由于数据链路层MTU的限制,对于较⼤的IP数据包要进⾏分包. 什么是MTU MTU相当于发快递时对包裹尺⼨的限制.这个限制是不同的数据链路对应的物理层,产⽣的限制. • 以太⽹帧中的数据⻓度规定最⼩46字节,最⼤1500字节,ARP数据包的⻓度不够46字节,要在后⾯补填 充…