Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing all variables value from a class

I have a class with information about a Person that looks something like this:

public class Contact {
    private String name;
    private String location;
    private String address;
    private String email;
    private String phone;
    private String fax;

    public String toString() {
        // Something here
    }
    // Getters and setters.
}

I want toString() to return this.name +" - "+ this.locations + ... for all variables. I was trying to implement it using reflection as shown from this question but I can't manage to print instance variables.

What is the correct way to solve this?

like image 365
Macarse Avatar asked Oct 06 '09 16:10

Macarse


People also ask

How do you display class variables in Python?

A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.

Which method is used to print the value of a variable?

Using printf function, we can print the value of a variable. In order to print the variable value, we must instruct the printf function the following details, 1.


Video Answer


4 Answers

From Implementing toString:

public String toString() {
  StringBuilder result = new StringBuilder();
  String newLine = System.getProperty("line.separator");

  result.append( this.getClass().getName() );
  result.append( " Object {" );
  result.append(newLine);

  //determine fields declared in this class only (no fields of superclass)
  Field[] fields = this.getClass().getDeclaredFields();

  //print field names paired with their values
  for ( Field field : fields  ) {
    result.append("  ");
    try {
      result.append( field.getName() );
      result.append(": ");
      //requires access to private field:
      result.append( field.get(this) );
    } catch ( IllegalAccessException ex ) {
      System.out.println(ex);
    }
    result.append(newLine);
  }
  result.append("}");

  return result.toString();
}
like image 96
cletus Avatar answered Oct 21 '22 10:10

cletus


Why do you want to reinvent the wheel when there are opensource that are already doing the job pretty nicely.

Both apache common-langs and spring support some very flexible builder pattern

For apache, here is how you do it reflectively

@Override
public String toString()
{
  return ToStringBuilder.reflectionToString(this);
}

Here is how you do it if you only want to print fields that you care about.

@Override
public String toString() 
{
    return new ToStringBuilder(this)
      .append("name", name)
      .append("location", location)
      .append("address", address)
      .toString(); 
}

You can go as far as "styling" your print output with non-default ToStringStyle or even customizing it with your own style.

I didn't personally try spring ToStringCreator api, but it looks very similar.

like image 43
Oscar Chan Avatar answered Oct 21 '22 08:10

Oscar Chan


If you are using Eclipse, this should be easy:

1.Press Alt+Shift+S

2.Choose "Generate toString()..."

Enjoy! You can have any template of toString()s.

This also works with getter/setters.

like image 38
Linerd Avatar answered Oct 21 '22 08:10

Linerd


Generic toString() one-liner, using reflection and style customization:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
  return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
like image 12
Stephane Chatre Avatar answered Oct 21 '22 08:10

Stephane Chatre