private <T> void setFiledValue(String fileName,Object value,Class<T> clz) throws IllegalAccessException, InstantiationException, InvocationTargetException { //该方式找不到对应字段不会报错 if(StringUtils.isEmpty(fileName)){ return; } //转成SetXXX方法名 char[] chars = fileName.toCharArray(); chars[0]=(char) (chars[0]-32); //首字母转大写 //拼接成方法名 String methodName="set"+String.copyValueOf(chars); T t = clz.newInstance();//获取对象 Method[] declaredMethods = clz.getDeclaredMethods(); for (Method method : declaredMethods) { String name = method.getName(); boolean equals = method.getName().equals(methodName); if(equals){ method.invoke(t,value); System.out.println(t.toString()); } } } private <T> void setFiledValue2(String fileName,Object value,Class<T> clz) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException { //该方法如果获取不到字段值就会抛异常 if(StringUtils.isEmpty(fileName)){ return; } Field field = clz.getDeclaredField(fileName);//获取字段 T t = clz.newInstance(); if(field!=null){ field.setAccessible(true);//修改作用域 field.set(t,value);//设置值 System.out.println(t.toString()); } } //设置用户 public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name=‘" + name + ‘\‘‘ + ‘}‘; } } @Test public void test2(){ //根据字段名字,反射设置值 try { setFiledValue2("name", "xiaoMing",User.class); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } }
原文:https://www.cnblogs.com/yangxiaohui227/p/11176192.html