java內省小記

來源:互聯網
上載者:User

標籤:for   pre   object   div   length   get   getc   person   method   

//為了讓程式員更好的操作javabean的屬性,JDK提供了一套API用來訪問某個屬性的setter或getter方法。這就是內省    //內省(Introspector)是java語言對javabean類屬性,方法和事件的一種標準處理方式。    //內省訪問javabean有兩種方法。        //設定javaBean屬性值。    public static void main(String[] args) throws Exception {        //1.方式一        /*//執行個體化一個person對象        Person beanObj = new Person();        //通過Introspector對象擷取Person對象的BeanInfo對象        BeanInfo beanInfoObject = Introspector.getBeanInfo(beanObj.getClass(),beanObj.getClass().getSuperclass());        //通過BeanInfoObject的getPropertyDescriptors方法,的到Bean中的所有屬性資訊。        propertyDescriptors = beanInfoObject.getPropertyDescriptors();        //便利屬性資訊,通過getName的到屬性名稱,通過getPropertyType得到屬性類型對象。        for (int i = 0; i <propertyDescriptors.length; i++) {                        String name = propertyDescriptors[i].getName();            Class<?> propertyType =  propertyDescriptors[i].getPropertyType();            System.out.println(name+"("+propertyType.getName()+")");        }*/                //方式二  直接通過PropertyDescriptor對象,擷取屬性資訊。                //建立person類的對象        Person p = new Person();        //通過屬性描述器,獲得那麼屬性描述資訊。        PropertyDescriptor pd = new PropertyDescriptor("name",p.getClass());        //擷取name屬性的setter方法。        Method methodName = pd.getWriteMethod();        //調用setter方法。設定name值        methodName.invoke(p,"小米");                System.out.println(p);

//相應的person類

private String name;    private int age;    public Person(){}    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String toString(){        return this.name+":"+this.age;    }

 

java內省小記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.