bean属性的类型如何为null?

问题描述:

在“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是否为空。何时和在什么情况下会发生?你能给个例子吗?

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方法,则使用标准访问器读取和写入值。

JavaDoc:如果类型是不支持 非索引访问的索引属性

返回null。

所以我猜如果属性类型是索引属性(如数组),它将返回null

如果您有像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; 
    } 
}