2011-08-24 105 views
8

在「Thinking in Java」一書中,有一個如何通過Reflection/Introspection獲取bean信息的例子。bean屬性的類型如何爲null?

BeanInfo bi = Introspector.getBeanInfo(Car.class, Object.class); 
for (PropertyDescriptor d: bi.getPropertyDescriptors()) { 
    Class<?> p = d.getPropertyType(); 
    if (p == null) continue; 
    [...] 
} 

在上述樣本的第4行中,檢查PropertyType是否爲空。何時和在什麼情況下會發生?你能給個例子嗎?

回答

2

PropertyDescriptor類國家getPropertyType方法的Javadoc:

結果可能是「空」,如果這是一個索引屬性是不 支持非索引訪問。

索引屬性是那些由值數組支持的屬性。除了標準的JavaBean訪問器方法外,索引屬性還可以通過指定索引來獲取/設置數組中的各個元素。 JavaBean的,可能因此,有索引的getter和setter方法:

public PropertyElement getPropertyName(int index) 
public void setPropertyName(int index, PropertyElement element) 

除了標準的getter和setter非索引訪問:

public PropertyElement[] getPropertyName() 
public void setPropertyName(PropertyElement element[]) 

,打算到Javadoc中的描述,如果你省略非索引訪問器,您可以獲得屬性描述符的屬性類型的返回值null

所以,如果你有以下品種一個JavaBean,你可以得到一個空的返回值:

class ExampleBean 
{ 

    ExampleBean() 
    { 
     this.elements = new String[10]; 
    } 

    private String[] elements; 

    // standard getters and setters for non-indexed access. Comment the lines in the double curly brackets, to have getPropertyType return null. 
    // {{ 
    public String[] getElements() 
    { 
     return elements; 
    } 

    public void setElements(String[] elements) 
    { 
     this.elements = elements; 
    } 
    // }} 

    // indexed getters and setters 
    public String getElements(int index) { 
     return this.elements[index]; 
    } 

    public void setElements(int index, String[] elements) 
    { 
     this.elements[index] = elements; 
    } 

} 

注意,而你可以單獨實現索引的屬性訪問,但不建議這樣做因此,如果您碰巧使用PropertyDescriptorgetReadMethodgetWriteMethod方法,則使用標準訪問器讀取和寫入值。

3

JavaDoc:如果類型是不支持 非索引訪問的索引屬性

返回null。

所以我猜如果屬性類型是索引屬性(如數組),它將返回null

2

如果您有像int getValue(int index)這樣的方法,則返回null。

以下代碼打印

double is null 
ints class [I 

類:

import java.beans.BeanInfo; 
import java.beans.IntrospectionException; 
import java.beans.Introspector; 
import java.beans.PropertyDescriptor; 

public class BeanInfos { 

public static void main(String[] args) { 

    try { 
     BeanInfo bi = Introspector.getBeanInfo(ClassA.class, Object.class); 
     for (PropertyDescriptor d : bi.getPropertyDescriptors()) { 
     Class<?> p = d.getPropertyType(); 
     if (p == null) 
      System.out.println(d.getName() + " is null"); 
     else 
      System.out.println(d.getName() + " " + p); 
     } 
    } catch (IntrospectionException e) { 
     e.printStackTrace(); 
    } 
    } 

} 

class ClassA { 
    private int[] ints; 
    private double[] doubles; 

    public int[] getInts() { 
    return ints; 
    } 

    public void setInts(int[] ints) { 
    this.ints = ints; 
    } 

    public double getDouble(int idx) { 
    return doubles[idx]; 
    } 

    public void setDoubles(double val, int idx) { 
    this.doubles[idx] = val; 
    } 
} 
相關問題