需求:根据表头列,显示列表内容。每一列在列表中的顺序可以随时调整。
id | name | age | score |
1 | c1 | 23 | 80.6 |
2 | c2 | 24 | 76 |
3 | c3 | 25 | 40.9 |
| | | |
id | name | score | age |
1 | c1 | 80.6 | 23 |
2 | c2 | 76 | 24 |
3 | c3 | 40.9 | 25 |
| | | |
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;
}
}