简体   繁体   English

Java:printstream的输出奇怪,为什么toString不转换?

[英]Java: Strange output with printstream, why toString doesn't convert?

I am not getting the result I expected when using toString on an object. 在对象上使用toString时,没有得到预期的结果。 (I have inherited the code). (我已经继承了代码)。

The goal is to print on a txt file the FiscalCode of a person. 目的是在一个txt文件上打印一个人的FiscalCode

Here is my object: 这是我的对象:

public class DatiPersonaFisica extends DatiPersona {

private String nome;
private String cognome;
private CodiceFiscale CF;
private String cell;
private Indirizzo domicilio;
}

And here Is my method to create and print the file: 这是我创建和打印文件的方法:

public class LoggerPersone  {

public static void Logger(DatiPersonaFisica p) throws FileNotFoundException{
FileOutputStream fs = new FileOutputStream("logPersoneFisicheInserite.txt",true);
PrintStream scrivi = new PrintStream(fs);
CodiceFiscale codfisc = p.getCF();
codfisc.toString();
scrivi.println(codfisc);
scrivi.close(); 
}

All seems to work fine but the output is: 一切似乎工作正常,但输出为:

data_view.CodiceFiscale@43ee5528 

which is not a fiscal code. 这不是财政法规。

The problem is that the class CodiceFiscale does not override Object's public String toString() method, and so you're seeing the String returned from Object's default method. 问题在于,类CodiceFiscale不会覆盖Object的public String toString()方法,因此您看到的是从Object的默认方法返回的String。

Instead consider either overriding the method yourself, if possible, or printing out the different fields of your CodiceFiscale object. 而是考虑自己重写方法(如果可能),或打印出CodiceFiscale对象的不同字段。 If you don't want to modify CodiceFiscale directly, consider extending it, and giving your child class a decent toString() method, one that returns important information. 如果您不想直接修改CodiceFiscale,请考虑对其进行扩展,并为子类提供一个不错的toString()方法,该方法返回重要信息。 You may need to use a " wrapper " class for this purpose. 为此,您可能需要使用“ 包装 ”类。

Having said that, I think that it is in general not recommended to use toString() in production code in this way. 话虽如此,我认为通常不建议以这种方式在生产代码中使用toString() The method is most useful and safest for debugging purposes. 该方法对于调试目的是最有用和最安全的。 An alternative is to create a static utility method that extracts all the needed information from the CodiceFiscale object passed in, and that returns a String of interest. 一种替代方法是创建一个静态实用程序方法,该方法从传入的CodiceFiscale对象中提取所有需要的信息,然后返回感兴趣的String。

Rather than depending on toString() for an object, you should consider adding a "getValue" method that returns what you want to put into the file. 您应该考虑添加“ getValue”方法来返回要放入文件的内容,而不是依赖于对象的toString() Go to the CodiceFiscale class source and add something like: 转到CodiceFiscale类源,并添加类似以下内容:

public String getFiscalCode() {
  return <string for fiscal code>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM