java 反射 设置_java 反射 根据属性 动态设置值

该博客演示了如何使用Java反射API动态地根据属性名称设置类实例的值。通过将输入字符串按特定分隔符拆分,匹配类的字段并进行赋值,实现了属性的动态更新。示例中创建了一个`ExceptionLog`类,并展示了如何设置其属性值。
摘要由CSDN通过智能技术生成

package com.jhl.jvm.lesson8;

import java.lang.reflect.Field;

/**

*

* @author jhl

* java 反射 根据属性 动态设置值 demo

*

*/

public class ExceptionLog {

private String exceptionLogId;

private String processingType;

private String type;

private String content;

public String getExceptionLogId() {

return exceptionLogId;

}

public void setExceptionLogId(String exceptionLogId) {

this.exceptionLogId = exceptionLogId;

}

public String getProcessingType() {

return processingType;

}

public void setProcessingType(String processingType) {

this.processingType = processingType;

}

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public String getContent() {

return content;

}

public void setContent(String content) {

this.content = content;

}

@SuppressWarnings("rawtypes")

public static void main(String[] args) throws Exception {

String exceptionInfo = "processingType=" + "加油!" + "#type=" + ""

+ "#content=" + "左良" + "#processingType=" + "11111"

+ "#recordType=";

ExceptionLog exceptionLog = new ExceptionLog();

Class cls = exceptionLog.getClass();

String[] str = exceptionInfo.split("#");

String log = "";//记录日志用

for (String s : str) {

String key = s.split("=")[0];

if ("recordType".equals(key))

log = key;

String value = s.split("=").length > 1 ? s.split("=")[1] : "";

for (Field field : cls.getDeclaredFields()) {

if (field.getName().equals(key)) {

field = cls.getDeclaredField(key);

field.setAccessible(true);

field.set(exceptionLog, value);// 动态设置值

break;

}

}

}

System.out.println("log=" + log);

System.out.println("exceptionLogId=" + exceptionLog.getExceptionLogId());

System.out.println("content=" + exceptionLog.getContent());

System.out.println("processingType=" + exceptionLog.getProcessingType());

System.out.println("type=" + exceptionLog.getType());

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值