Reputation: 137
I am new to java and JSP, i have doubt about accessing the method of tag class. i have created 3 custom tags namely Primary, Secondary, Axis. so i can access
<pre:Primary>
<pre:Axis/>
</pre:Primary>
<pre:Secondary>
<Pre:Axis/>
</pre:Secondary>
In Axis Tag class i have to access the parent methods, in this case primary, secondary is parent for Axis tag. In both parent class, i have method addItem(), i am calling the method as below in axis class.
Object parent=null;
try{
parent = (PrimaryWrapper)getParent();
}catch(Exception e){
parent = (SecondaryWrapper)getParent();
}
parent.addItem(axisItem);
but this is shows error, "The method addItem(StringBuilder) is undefined for the type Object", i know in try, catch only the scope of parent is changing to primary/secondary, hence the error occurs. but i have to access the appropriate addItem method based on Primary, Secondary. is it Possible? Or i am doing wrong.
Thanks in advance
Upvotes: 2
Views: 296
Reputation: 2924
The problem is the parent
variable is of class Object
, so anything you assign to it, you can only use the Object
's methods. I see basically two possible solutions.
Quick and dirty
Object parent = getParent();
if (parent instanceof PrimaryWrapper) {
((PrimaryWrapper) parent).addItem(axisItem);
} else if (parent instanceof SecondaryWrapper) {
((SecondaryWrapper) parent).addItem(axisItem);
} else {
// log error?
}
Better - using Interface
// define an interface
public interface ItemContainer {
void addItem(StringBuilder item);
}
// change your Wrappers to implement the interface, i.e.
public class PrimaryWrapper extends ... implements ItemContainer {
// ... your code, just add @Override annotation to the addItem(...) method
}
// and
public class SecondaryWrapper extends ... implements ItemContainer {
// ... your code, just add @Override annotation to the addItem(...) method
}
// and finally, fix the AxisTag code
ItemContainer parent = (ItemContainer) getParent();
parent.addItem(axisItem);
Or, as mentioned in comment from Hacketo, instead of creating and interface, you could create an common ancestor class (e.g. Wrapper
) and implement the common methods there. The code of AxisTag
would be similar to the above solution with interface.
Upvotes: 1