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