在Java中,我可以整合两个使用JspWriter和其他PrintWriter的类似函数吗?

Bri*_*ler 6 java polymorphism jsp casting printwriter

我有以下类,您将看到它有一个相当冗余的formatNameAndAddress方法:

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>");
 }
}
Run Code Online (Sandbox Code Playgroud)

我想重写该类以使用通用方法,如:

     // 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>");
 }
Run Code Online (Sandbox Code Playgroud)

但是,我不能完全这样做因为Object没有print()和println()方法.如果我将输出转换为JspWriter或PrintWriter,我有时会以错误的方式将其输出.

我想我需要做的是以某种方式将对象类型作为变量传递,然后使用该变量来确定如何投射.这可能吗?如果是这样,怎么样?如果没有,那么什么是好的解决方案?

Mic*_*ker 5

这可能会奏效:

public void formatNameAndAddress(JspWriter out) throws java.io.IOException {
    formatNameAndAddress(new PrintWriter(out));
}
Run Code Online (Sandbox Code Playgroud)