我有以下类,正如您将看到的那样,它有一个相当多余的 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,有时我会以错误的方式转换它。
我想我需要做的是以某种方式将对象类型作为变量传递,然后使用该变量来确定如何转换。这可能吗?如果是这样,怎么做?如果没有,什么是好的解决方案?