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;
    }
}
相关推荐
Tiger Z7 分钟前
R 语言科研绘图 --- 密度图-汇总
开发语言·程序人生·r语言·贴图
Python数据分析与机器学习13 分钟前
《基于深度学习的高分卫星图像配准模型研发与应用》开题报告
图像处理·人工智能·python·深度学习·神经网络·机器学习
lllsure33 分钟前
【快速入门】MyBatis
java·后端·mybatis
叶雅茗35 分钟前
PHP语言的区块链扩展性
开发语言·后端·golang
程序员总部39 分钟前
PyCharm如何有效地添加源与库?
ide·python·pycharm
LCY13339 分钟前
django中间件说明
python·中间件·django
蹦蹦跳跳真可爱5891 小时前
Python----数据分析(Pandas四:一维数组Series的统计计算,分组和聚合)
python·数据分析·pandas
爱学习的学姐1 小时前
【精品源码】Java宠物领养网站+SpringBoot+VUE+前后端分离
java·spring boot·宠物
双叶8362 小时前
(C语言)写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和(递归函数)
c语言·开发语言·数据结构·算法·游戏
字节源流2 小时前
【SpringMVC】常用注解:@SessionAttributes
java·服务器·前端