类加载器及反射机制(二)-根据对象属性读取属性值

需求:根据表头列,显示列表内容。每一列在列表中的顺序可以随时调整。

 

idnameagescore
1c12380.6
2c22476
3c32540.9
    

idnamescoreage
1c180.623
2c27624
3c340.925
    

 

package cn.com.chenlly;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @ Class ReflectionField.java
 * @ Description  使用发射机制动态得到对象属性值
 * @ Company oppo
 * @ author Chenlly E-mail: 
 * @ Version 1.0
 * @ Date Jan 21, 2010 9:55:05 AM
 */
public class ReflectionField {
 

//定义表头,当需要改变列的显示顺序时,只需要改变表头中每一列的位置。
 public List<String> defineTitle(){
  List<String> title = new ArrayList<String>();
  title.add("ID");
  title.add("NAME");
  title.add("AGE");
  title.add("SCORE");
  return title;
 }
 
 public Object getProperty(Object obj, String fieldName) throws IllegalArgumentException, IllegalAccessException{
  Class owner = obj.getClass();
  Field []fields = owner.getDeclaredFields();
  Object value=null;
  for(Field field:fields){
   if(field.getName().toUpperCase().equals(fieldName)){
    field.setAccessible(true);
    value = field.get(obj);
   }
   
  }
  //未读到属性值,则读取父类属性值
  if(value==null){
   Class superClass = owner.getSuperclass();
   if(superClass !=null){
    fields = superClass.getDeclaredFields();
    for(Field field:fields){
     if(field.getName().toUpperCase().equals(fieldName)){
      field.setAccessible(true);
      value = field.get(obj);
     }
    }
   }
  }
  return value;
 }
 
 
 public static void main(String []args){
  Student s1 = new Student(1,"c1",23,67.98);
  Student s2 = new Student(2,"c2",20,90.8);
  List<Student> list = new ArrayList<Student>();
  list.add(s1);
  list.add(s2);
  ReflectionField rf = new ReflectionField();
  List<String> titles = rf.defineTitle();
  Object value = null;
  try {
   for(Student student:list){
    for (String title:titles){
     value = rf.getProperty(student, title);
     System.out.print(value+"  ");
    }
    System.out.println();
   }
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  }
 }
 
}


class Persion{
 private int id;
 
 private String name;
 
 private int age;
 
 public Persion(int id,String name, int age){
  this.id = id;
  this.name = name;
  this.age = age;
 }
}
class Student extends Persion{
 private Double score;
 public Student(int id,String name,int age,Double score){
  super(id,name,age);
  this.score = score;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值