版权声明: https://blog.csdn.net/RAVEEE/article/details/85266589
首先强烈不建议使用反射的方法来对对象的字段进行赋值,这里也是为了项目需要,如果有什么更好的方法欢迎留言
package com.secure.utils;
import java.lang.reflect.Field;
import org.eclipse.jdt.internal.compiler.codegen.ObjectCache;
import com.secure.pojo.SoftWare;
/**
*
* <p>
* Title: UpdateTool.java</p>
* <p>
* Description: </p>
* @author Ray
** @date 2018年12月26日
* @version 1.0
*/
public class UpdateTool {
public static SoftWare formate(SoftWare softWare) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
Field[] fileds = softWare.getClass().getDeclaredFields();// 获得所有字段;
SoftWare s = new SoftWare();
for (Field f : fileds) {
f.setAccessible(true);
String name = f.getName();
String value = (String) f.get(softWare);
if (value != null) {
Field newF=s.getClass().getDeclaredField(name);
newF.setAccessible(true);
newF.set(s, "哈哈哈哈哈");
newF.setAccessible(false);
}
}
return s;
}
public static void main(String[] arg) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
SoftWare s = new SoftWare();
s.setName("sd");
s=UpdateTool.formate(s);
System.out.println(s);
}
}
设置完成,如图所示: