Reusing a JavaBean class in other beans
I have two objects Node1 and Node2 and both are using Bean1 (JavaBean).
I am trying to include the properties of Bean1 in both Node1 and Node2 without manually duplicating the properties of Bean1. Also, I am trying to reuse the BeanInfo of Bean1 in both the objects as well.
I was thinking of using cglib but is it possible at all?
More details: Nodes are modeling job inputs i.e., Node1 is input for Job1 and so on. Input types may have a common type inside, which is Bean1. Say, Bean1 has a property bean1Prop and Node1 has a property node1Prop and Node2 has a property node2Prop.
I would need something like Node1{ node1Prop, bean1Prop } and Node2{ node2Prop, bean1Prop }. Note that each node will have a separate instance of Bean1 during init. Now, I can get the properties manually by delegation which I do not want to do to avoid code duplication. I just want to tell each node class that I want to use the bean properties of Bean1.
cglib seems to be able to create such objects at runtime. But I guess the runtime type would be just an Object?
Also, Bean1 has a beaninfo class which I want to reuse in Node1BeanInfo (by getAdditionalBeanInfo()) and similarly in Node2BeanInfo.
I am not sure if Node1BeanInfo and Node2BeanInfo would be recognized (by a JavaBeanTool) as the beaninfo classes for the runtime-generated objects by cglib.
I must add that I have never used cglib before.
My primary goal is to avoid code duplication which will be significant in this case when a com开发者_StackOverflowmon type is used for many job inputs (which is very common).
I appreciate your thoughts on this.
I'm not sure that you mean, but it sounds like this:
public class Node1 {
private Bean1 bean1;
public Node1(Bean1 bean1) {
this.bean1 = bean1;
}
}
public class Node2 {
private Bean1 bean1;
public Node2(Bean1 bean1) {
this.bean1 = bean1;
}
}
Just be careful: if Node1 and Node2 both point to the same Bean1 instance, you'll have to worry about changes by one class immediately being visible to the other. You can cause yourself some nasty surprises with this arrangement.
Yes, Beans are a good way to reuse code.
No, there's no reason Node1 and Node2 can't share Bean1 to implement the same functionality. In fact, they should.
So far, so good...
If you want to share STATE between your nodes, however, your first question is HOW you wish to store the state.
SIMPLEST APPROACH: write a clear-text property file
ALTERNATIVE APPROACH: store properties in a database
With either approach, you could: a) have the bean read the property at startup (from database, property file, etc) b) have your client query the bean for the property value
STILL ANOTHER ALTERNATIVE: Just hard code the values in your bean :)
精彩评论