gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:23 25 4
gpt4 key购买 nike

我有以下类,您将看到它有一个相当多余的 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,有时我会以错误的方式进行转换。

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

最佳答案

这可能会起作用:

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

关于java - 在 Java 中,我可以合并两个使用 JspWriter 和另一个 PrintWriter 的相似函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3849768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com