JAVA Reflection API 可以检查运行时的对象和动态更新字段与调用方法.

package usingj2ee.reflect;

public class Person {

public String firstName;
public String middleName;
public String lastName;

public Person() {
// TODO 自动生成构造函数存根
}

public Person(String aFirstName,String aMiddleName,String aLastName){

firstName = aFirstName;
middleName = aMiddleName;
lastName = aLastName;
}

public String getFirstName(){
return firstName;
}

public void setFirstName(String theFirstName){
firstName = theFirstName;
}

public String getMiddleName(){
return middleName;
}

public void setMiddleName(String theMiddleName){
middleName = theMiddleName;
}

public String getLastName(){
return lastName;
}

public void setLastName(String theLastName){
lastName = theLastName;
}

public String toString(){

StringBuffer buff = new StringBuffer();

if(firstName != null){

buff.append(firstName);
buff.append(' ');
}
if(middleName != null){

buff.append(middleName);
buff.append(' ');
}
if(lastName != null){

     buff.append(lastName);
  
        }

return buff.toString();
}


}

package usingj2ee.reflect;

import java.lang.reflect.*;

public class ShowPersonFields {

public static void main(String[] args){

try{
Person person = new Person(
"xiaona","haohao","dongdong");

Class personClass = person.getClass();

Field[] personFields = personClass.getDeclaredFields();

for(int i=0;i<personFields.length;i++){

String fieldName = personFields<i>.getName();

String fieldValue = (String)personFields<i>.get(person);

System.out.println(fieldName+
"="+fieldValue);

}
}
catch(Exception exc){
exc.printStackTrace();
}
}

}

 

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

认证码:
(数字如不清楚,请刷新一次)


Copyright@2004-2010 powered by YuLog