简体   繁体   中英

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

I am not getting the result I expected when using toString on an object. (I have inherited the code).

The goal is to print on a txt file the FiscalCode of a person.

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.

Instead consider either overriding the method yourself, if possible, or printing out the different fields of your CodiceFiscale object. 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. 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. 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.

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. Go to the CodiceFiscale class source and add something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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