我在Java中使用了一些我不太懂的功能,所以我想阅读它以便我可以更有效地使用它.问题是我不知道它叫什么,因此很难获得更多信息:
我有一个这样Foo定义的类:
private String _name;
private Bar _bar;
//getters and setters
Run Code Online (Sandbox Code Playgroud)
而且Bar:
private String _code;
//getters and setters
public String get_isCodeSmith()
{
boolean rVal = _code.toLowerCase().contains("smith");
return rVal;
}
Run Code Online (Sandbox Code Playgroud)
不知何故,在我的JSP页面中(当我Session调用一个变量时Foo),我能够编写如下的逻辑标记:
<logic:equal name="Foo" property="_bar._isCodeSmith" value="true">
Run Code Online (Sandbox Code Playgroud)
即使_isCodeSmith我的类中没有属性Bar,它也会get_isCodeSmith()自动运行该方法.
这叫什么,我在哪里可以找到更多?
这是Javabeans机制.属性不是由字段标识,而是由getter(访问器)和/或setter(mutator)方法标识.
有关更多技术信息,请阅读JavaBeans规范
或者看看这个简单的测试类:
public class TestBean {
private String complete;
public String getComplete() { return complete; }
public void setComplete(final String complete) { this.complete = complete; }
private String getterOnly;
public String getGetterOnly() { return getterOnly; }
private String setterOnly;
public void setSetterOnly(final String setterOnly) { this.setterOnly = setterOnly; }
public String getNoBackingField() { return ""; }
}
Run Code Online (Sandbox Code Playgroud)
和简单的JavaBeans分析:
public class Test {
public static void analyzeBeanProperties(final Class<?> clazz) throws Exception {
for (final PropertyDescriptor propertyDescriptor
: Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors()) {
System.out.println("Property name: " + propertyDescriptor.getName());
System.out.println("Getter method: " + propertyDescriptor.getReadMethod());
System.out.println("Setter method: " + propertyDescriptor.getWriteMethod());
System.out.println();
}
}
public static void main(final String[] args) throws Exception {
analyzeBeanProperties(TestBean.class);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Property name: complete
Getter method: public java.lang.String test.bean.TestBean.getComplete()
Setter method: public void test.bean.TestBean.setComplete(java.lang.String)
Property name: getterOnly
Getter method: public java.lang.String test.bean.TestBean.getGetterOnly()
Setter method: null
Property name: noBackingField
Getter method: public java.lang.String test.bean.TestBean.getNoBackingField()
Setter method: null
Property name: setterOnly
Getter method: null
Setter method: public void test.bean.TestBean.setSetterOnly(java.lang.String)
Run Code Online (Sandbox Code Playgroud)