随笔-2  评论-0  文章-0  trackbacks-0
转自:http://technet.microsoft.com/zh-cn/library/aa989722 

功能:Gets the field (public, private, or protected) with the given name. 

原型:public java.lang.reflect.Field getDeclaredField(java.lang.String fieldName)

Example:
// class_getdeclaredfield.jsl

import java.lang.reflect.Field;
import java.util.Date;

public class Program
{
    public static void main(String[] args)
    {
        try
        {
            // Get the Class object associated with this class.
            Program program = new Program();
            Class progClass = program.getClass();

            // Get the field named str.
            Field strField = progClass.getDeclaredField("str");
            System.out.println("Field found: " + strField.toString());

            // Get the field named date.
            Field dateField = progClass.getDeclaredField("date");
            System.out.println("Field found: " + dateField.toString());

            // Get the field named i.
            Field iField = progClass.getDeclaredField("i");
            System.out.println("Field found: " + iField.toString());
        }
        catch (NoSuchFieldException ex)
        {
            System.out.println(ex.toString());
        }
    }

    public Program()
    {
    }

    public Program(String str, Date date, int i)
    {
        this.str = str;
        this.date = date;
        this.i = i;
    }

    public String str = "Hello";
    private Date date = new Date();
    protected int i = 0;
}

/*
Output:
Field found: public java.lang.String Program.str
Field found: private java.util.Date Program.date
Field found: protected int Program.i
*/

注:
getFields()获得某个类的所有的公共(public)的字段,包括父类。 
getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。 
posted on 2012-07-20 13:01 dping 阅读(530) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理