小编典典

在Java中,我可以合并两个使用JspWriter和另一个PrintWriter的相似函数吗?

jsp

我有以下类,如您所见,它具有相当冗余的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>");
 }
}

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

     // 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>");
 }

但是,我无法完全做到这一点,因为Object没有print()和println()方法。如果将输出强制转换为JspWriter或PrintWriter,有时会以错误的方式强制转换。

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


阅读 309

收藏
2020-06-10

共1个答案

小编典典

这可能会起作用:

public void formatNameAndAddress(JspWriter out) throws java.io.IOException {
    formatNameAndAddress(new PrintWriter(out));
}
2020-06-10