I have the following class, which, as you will see, has a rather redundant formatNameAndAddress method:
package hu.flux.helper; import java.io.PrintWriter; import javax.servlet.jsp.JspWriter; // A holder for formatting data public class NameAndAddress { public String firstName; public String middleName; public String lastName; public String address1; public String address2; public String city; public String state; public String zip; // Print out the name and address. public void formatNameAndAddress(JspWriter out) throws java.io.IOException { out.println("<PRE>"); out.print(firstName); // Print the middle name only if it contains data. if ((middleName != null) && (middleName.length() > 0)) {out.print(" " + middleName);} out.println(" " + lastName); out.println(" " + address1); if ((address2 != null) && (address2.length() > 0)) out.println(" " + address2); out.println(city + ", " + state + " " + zip); out.println("</PRE>"); } public void formatName(PrintWriter out) { out.println("<PRE>"); out.print(firstName); // Print the middle name only if it contains data. if ((middleName != null) && (middleName.length() > 0)) {out.print(" " + middleName);} out.println(" " + lastName); out.println(" " + address1); if ((address2 != null) && (address2.length() > 0)) out.println(" " + address2); out.println(city + ", " + state + " " + zip); out.println("</PRE>"); } }
I would like to rewrite the class to use a generic method, for example:
// Print out the name and address. private void genericFormatNameAndAddress(Object out) { out.println("<PRE>"); out.print(firstName); // Print the middle name only if it contains data. if ((middleName != null) && (middleName.length() > 0)) {out.print(" " + middleName);} out.println(" " + lastName); out.println(" " + address1); if ((address2 != null) && (address2.length() > 0)) out.println(" " + address2); out.println(city + ", " + state + " " + zip); out.println("</PRE>"); }
But I canβt do it exactly like that, because Object does not have print () and println () methods. If I pass the output to JspWriter or PrintWriter, sometimes I get it wrong.
I guess what I need to do is somehow pass the type of the object as a variable, and then use the variable to determine how to distinguish it. Is it possible? If so, how? If not, what would be a good solution?
java polymorphism casting jsp printwriter
Brian kessler
source share