标签:java String 后端 初始值 test import Test return public
当我们需要测试保存时,自己new对象很麻烦,所以我写了一个通用方法,来自动设置初始值
现在还只能设置String类型,之后再增加设置其他类型。直接上代码。
package com.setValueToObject; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.transaction.NotSupportedException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * TODO * * @author sean * @date 2020/5/13 11:51 AM */ public class ObjectParamOprate<T> { private final static Logger logger = LoggerFactory.getLogger(ObjectParamOprate.class); /** * 只给T对象中的String类型的属性赋值 * @param t * @return * @throws InvocationTargetException * @throws IllegalAccessException * @throws NotSupportedException */ public T setStringVaule(T t) throws InvocationTargetException, IllegalAccessException { Field[] f = t.getClass().getDeclaredFields();; //给test对象赋值 for (int i = 0; i < f.length; i++) { //获取属相名 String attributeName = f[i].getName(); //将属性名的首字母变为大写,为执行set/get方法做准备 String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); try { //获取Test类当前属性的setXXX方法(私有和公有方法) /*Method setMethod=Test.class.getDeclaredMethod("set"+methodName);*/ //获取Test类当前属性的setXXX方法(只能获取公有方法) Method setMethod = t.getClass().getMethod("set" + methodName, String.class); //执行该set方法 setMethod.invoke(t, attributeName); } catch (NoSuchMethodException e) { logger.warn("不能给[{}]赋值,请自己赋值", attributeName); } } return t; } public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NotSupportedException { Test test = new Test(); ObjectParamOprate<Test> t = new ObjectParamOprate<>(); t.setStringVaule(test); System.out.println(JSON.toJSONString(test)); } }
package com.setValueToObject; import java.math.BigDecimal; public class Test { private String aa; private int bb; private String cc; public String dd; public Test test; public BigDecimal ee; private String ff; public String getFf() { return ff; } public void setFf(String ff) { this.ff = ff; } public String getAa() { return aa; } public void setAa(String aa) { this.aa = aa; } public int getBb() { return bb; } public void setBb(int bb) { this.bb = bb; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public Test getTest() { return test; } public void setTest(Test test) { this.test = test; } public BigDecimal getEe() { return ee; } public void setEe(BigDecimal ee) { this.ee = ee; } }
标签:java,String,后端,初始值,test,import,Test,return,public 来源: https://www.cnblogs.com/sean-zeng/p/12881962.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。