JSF: Why do UIComponents need a no-args constructor?
Without one, component renders ok, however, using AJAX with re-renderable target within it fails (IllegalStateException).
I guess UIComponents need to accord to JavaBeans spec. But why do they need the non-args constructor? If I call UIComponent
from a template, I understand that runtime needs to initialize a class with a non-args constructor and then set any properties, but in this case I was adding the component programmatically as:
MyComponent comp = new MyComponent("foo", "bar");
g开发者_开发知识库etChildren().add(comp);
So I wasn't calling a non-args constructor, and I don't know why JSF would either as AJAX should only re-render the component, not create a new instance from the component class?
You aren't calling it, but JSF might need to instantiate the component.
Take a look at the StateHolder
interface (which is implemented by UIComponent
). It explicitly states that a no-arg constructor is needed. And that's because this is a custom mechanism of saving and restoring state.
The thing is that JSF components are automatically serialized and de-serialized between requests. Default constructors (while in theory not absolutely necessary) make this a lot easier and are required by the Serializable API.
From the Serializable docs:
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
The JSF framework must be able to instantiate new instances of UIComponent
classes. There is no requirement for the UI tree to be held in RAM between requests and when this is the case, reflection is used to restore it.
UIComponent
implementations do not implement Serializable
and are not JavaBeans (per the strict definition). Implementing Serializable
would not be useful because components can have a 1:n relationship with their state (e.g. they are the child of a repeating control).
精彩评论