How are get and set methods on javabeans called by frameworks?
If you have a bean with a getFoo
method, how开发者_运维问答 does whatever framework you're using know how to call the getFoo
method when you ask for the value of foo
? Is this done using the reflection API? Or is it somehow done using annotations? Obviously I know how you can derive the method given the name of the property, I just don't know how the method is invoked.
Java uses "properties" by method name convention. For a property camelCase
of type T
you should define one or both of public T getCamelCase()
and public void setCamelCase(T t)
. You can test properties on a bean with this code:
Introspector.getBeanInfo (bean.getClass ()).getPropertyDescriptors ();
Note that because properties are not first-class objects and rely on naming convention, it is easy to accidentally break such pseudoproperty. E.g. if you define setFoo(int)
and setFoo(int, boolean)
there will be no property foo
in your class.
The actual method invocation is indeed done through reflection. You can have for instance a look at BeanUtil and more especally MethodUtil sources. To invoke a method reflectively, you use
method.invoke( bean, parameters );
See the reflection tutorial for examples.
精彩评论