java从入门到精髓 - 反射Field

import java.lang.reflect.Field;
public class FieldTest {

    
int i;
    
public float f;
    
protected boolean b;
    
private String s;
    
    
public FieldTest()
    {
        i
=0;
        f
=0.0f;
        b 
= true;
        s 
= "";
    }
    
public static void main(String[] args){
        
//进行类实例化:
        FieldTest fieldTest = new FieldTest();
        
        Field[] declaredFields 
= FieldTest.class.getDeclaredFields();
        
for(int i=0;i<declaredFields.length;i++){
            Field field 
= declaredFields[i];
            System.out.println(
"名称为:"+field.getName());
            Class fieldType 
= field.getType();
            System.out.println(
"类型为:"+field.getType());
            
boolean isTurn = true;
            
while(isTurn)
            {
                
try{
                    isTurn 
= false;
                    System.out.println(
"修改前的值为:"+ field.get(fieldTest));
                    
if(fieldType.equals(int.class))
                    {
                        System.out.println(
"利用setInt()方法修改成员变量的值.");
                        field.setInt(fieldTest, 
124);
                    }
                    
else if(fieldType.equals(float.class))
                    {
                        System.out.println(
"利用setFloat()方法修改成员变量的值.");
                        field.setFloat(fieldTest, 
9.9f);
                    }
else if(fieldType.equals(boolean.class))
                    {
                        System.out.println(
"利用setBoolean()方法修改成员变量的值.");
                        field.setBoolean(fieldTest, 
false);
                    }
                    
else
                    {
                        System.out.println(
"利用set()方法修改成员变量的值.");
                        field.set(fieldTest, 
"NWQ");
                    }
                    System.out.println(
"修改后的值为:"+field.get(fieldTest));
                }
catch(Exception e)
                {
                    System.out.println(
"在设置成员变量时发生异常,执行setAccessible()方法.");
                    field.setAccessible(
true);
                    isTurn 
= true;
                }
            }
            System.out.println(
"**************");
        }
    }
}

 

posted @ 2010-09-01 14:10  叮当小马  阅读(6197)  评论(0编辑  收藏  举报