java 反射 根据属性 动态设置值
2015-03-06 00:02
323 查看
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;
}
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通过反射机制动态设置对象属性值的方法
- Java通过反射机制动态设置对象属性值
- Java反射:根据方法名动态调用方法,解决商品动态属性取值问题。
- Java反射:根据属性名得到其Set方法设置它的值
- Java中用反射的方式获取类中的所有属性和方法,以及获取属性的默认值,设置属性的默认值
- Android 通过Java代码生成创建界面。动态生成View,动态设置View属性。addRules详解
- 数组属性,根据参数动态设置类中数组的长度!构造函数传入数组长度!并初始化数组!
- Java反射得到属性的值和设置属性的值
- Java反射得到属性的值和设置属性的值
- Java反射得到属性的值和设置属性的值(转)
- Java反射得到属性的值和设置属性的值
- Java反射根据不同方法名动态调用不同的方法(实例)
- Android 在Java代码中设置style属性--使用代码创建ProgressBar对象(反射机制)
- Java反射得到属性的值和设置属性的值
- 如何利用java的反射机制动态的取得对象的属性?
- 反射机制_介绍_Class对象获取_动态操作_构造器_方法_属性JAVA211-212
- JAVA的动态属性反射(reflect)功能基础
- 利用JAVA的动态属性之反射原理实现一个简单AOP容器 - AOP的实现原理分析
- 遍历类的所有属性和根据属性名动态设置属性值
- java反射动态获取字段名并设置字段值