1.4 java反射机制 简单的java反射机制实践

这是一个项目用于学习反射

第一个demo是利用反射构建一个对象转换为JSON

第二个demo是用于利用类的名字以及方法名就可以直接执行的实例

java 复制代码
package com.zy.reflectiondemo.utils;

import com.zy.reflectiondemo.annotation.JsonField;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
/***
该案例是一个利用反射获取对象的所有段的值,并且将他输出为json的案例
 ***/

public class JsonSerializer {



    public static String serialize(Object obj)   {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if(field.isAnnotationPresent(JsonField.class)){
                field.setAccessible(true);
                JsonField annotation = field.getAnnotation(JsonField.class);
                String key="";
                if (annotation.value().isEmpty()) {
                  key=field.getName();
                }
                else {
                key=annotation.value();
                }
                try {
                    Object o = field.get(obj);
                    map.put(key,o);

                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }


        }
        System.out.println(map);
        return  toJsonString(map);
    }

    private static String toJsonString(Map<String, Object> jsonElements) {
        StringJoiner json = new StringJoiner(",", "{", "}");
        for (Map.Entry<String, Object> entry : jsonElements.entrySet()) {
            json.add("\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"");
        }
        return json.toString();
    }
}
java 复制代码
package com.zy.reflectiondemo.utils;

import com.zy.reflectiondemo.POJO.User;

import java.lang.reflect.Method;

/***
 * 该方法利用反射,输入方法名称,以及方法参数,就可以执行方法
 */
public class Myinvoke {
    public static Object MyinvokeMethod(String classname,String methodname,Class<?> []paratypes,Object[]args) throws  Exception {
        Class<?> clazz = Class.forName(classname);
        Method method = clazz.getMethod(methodname, paratypes);
        Object instance = clazz.getDeclaredConstructor().newInstance();
        return method.invoke(instance,args);
       
    }
    public static void main(String[]args) throws Exception {
        String classname = JsonSerializer.class.getName();
        User user=new User(123L,"zy",23,"123");

        MyinvokeMethod(classname,"serialize",new Class<?>[]{Object.class},  new Object[] {user} );
    }
}
java 复制代码
package com.zy.reflectiondemo.annotation;

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.FIELD)
public @interface JsonField {
    String value() default "";
}
java 复制代码
package com.zy.reflectiondemo.POJO;

import com.zy.reflectiondemo.annotation.JsonField;

public class User {
    @JsonField("id")
    private Long userId;

    @JsonField
    private String name;

    @JsonField("age")
    private int userAge;

    private String password;  // 不标注的字段将被忽略

    public User(Long userId, String name, int userAge, String password) {
        this.userId = userId;
        this.name = name;
        this.userAge = userAge;
        this.password = password;
    }
}
相关推荐
whltaoin4 分钟前
【JAVA全栈项目】弧图图-智能图床 SpringBoot+Vue3 :[框架开荒:一文全步骤打通前后端项目全流程]
java·spring boot·vue·开源项目·全栈·cos
gfdgd xi33 分钟前
GXDE 内核管理器 1.0.1——修复bug、支持loong64
android·linux·运维·python·ubuntu·bug
Fu1co39 分钟前
【Spring Boot】Spring Boot解决循环依赖
java·spring boot·spring
国服第二切图仔1 小时前
Rust中泛型函数实现不同类型数据的比较
开发语言·后端·rust
递归不收敛1 小时前
专属虚拟环境:Hugging Face数据集批量下载(无登录+国内加速)完整指南
人工智能·笔记·git·python·学习·pycharm
我是小邵1 小时前
主流数据分析工具全景对比:Excel / Python / R / Power BI / Tableau / Qlik / Snowflake
python·数据分析·excel
我命由我123452 小时前
Derby - Derby 服务器(Derby 概述、Derby 服务器下载与启动、Derby 连接数据库与创建数据表、Derby 数据库操作)
java·运维·服务器·数据库·后端·java-ee·后端框架
技术砖家--Felix2 小时前
Spring Boot入门篇:快速搭建你的第一个Spring Boot应用
java·开发语言·音视频
国服第二切图仔2 小时前
Rust开发之使用Trait对象实现多态
开发语言·算法·rust
Yolo566Q2 小时前
Python驱动的无人机生态三维建模与碳储/生物量/LULC估算全流程实战技术
开发语言·python·无人机