Java反射之从对象获取值
生活随笔
收集整理的这篇文章主要介绍了
Java反射之从对象获取值
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
我们在开发的过程中,可能会遇到需要动态地通过字符串获取某个值,该值来自于某个对象。
利用反射可以,方便获取。该类可提取为工具类,供众多类调用。
getValueFormObject方法就是从Object对象中获取该对象的属性名称当中,与fileName相同的值。
ReflectUtil.java
import java.lang.reflect.Field;public class ReflectUtil {public static Object getValueFormObject(Object object, String fieldName) {if (object==null){ // LOG.error("the fields is wrong,object is null,fieldName is "+fieldName);System.out.println("the fields is wrong,object is null,fieldName is "+fieldName);return null;}if(fieldName==null||fieldName=="") { // LOG.error("the fields is wrong,object is null,object is "+object.toString());System.out.println("the fields is wrong,object is null,fieldName is "+fieldName);return null;}Field field;try {field = object.getClass().getDeclaredField(fieldName);if (field != null) {field.setAccessible(true);return field.get(object);}} catch (NoSuchFieldException | IllegalAccessException e) { // LOG.error("Get Value Form Object Wrong");System.out.println("Get Value Form Object Wrong");}return null;}public static void main(String[] args) {Student student = new Student(1,"kangyucheng");Object obj1 = ReflectUtil.getValueFormObject(student, "name");Object obj2 = ReflectUtil.getValueFormObject(student, "id");System.out.println(obj1.toString());System.out.println(obj2.toString());}}在测试当中我们用到的学生类:
Student.java
public class Student {private Integer id;private String name;public Student(Integer id, String name) {this.id = id;this.name = name;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}测试结果:
| kangyucheng 1 |
总结
以上是生活随笔为你收集整理的Java反射之从对象获取值的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 百练OJ:4016:班级排名
- 下一篇: Java反射之将对象转成map