利用反射技術動態獲取任意Java類實例的屬性值

package org.apache.easframework.core.entity.impl;

import java.lang.reflect.Field;

public class TestEntity {
 
 private String code;
 private String name;
 
 public void setCode(String code)
 {
  this.code = code;
 }
 
 public String getCode()
 {
  return this.code;
 }
 
 public void setName(String name)
 {
  this.name = name;
 }
 
 public String getName()
 {
  return this.name;
 }
 
 public static void main(String[] args) throws SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException
 {
  TestEntity obj = new TestEntity();
  obj.setName("name value");
  obj.setCode("code value");
  Field[] fds = Class.forName
  ("org.apache.easframework.core.entity.impl.TestEntity").getDeclaredFields();
  
  System.out.println(fds.length);
  for(int i=0;i<fds.length;i++)
  {
   System.out.println(fds[i].get(obj));
   
  }
 }

}

發佈了14 篇原創文章 · 獲贊 2 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章