码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-06 01:06:16      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:反射动态设置属性值

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());
}

}

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

标签:反射动态设置属性值

原文地址:http://blog.csdn.net/jihuanliang/article/details/44089361

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!