3

I want to generate toString() method for a class extending an other one. But in generate toString() dialog, there is no checkbox for inherited fields (see picture below)

enter image description here

What's the problem here ?

Community
  • 1
  • 1
mounaim
  • 1,132
  • 7
  • 29
  • 56

4 Answers4

6

The Inherited fields option will turn out if:

  • You are extending a class with inheritable fields, i.e. public, protected (or package-protected within the same package)
  • You are generating the toString method contextually to a right-click when your cursor is within the child class

The latter can be confusing: it's not where you right-click, but where your actual cursor is, that determines for which class the toString (et al.) method should be generated.

Mena
  • 47,782
  • 11
  • 87
  • 106
3

You have to write a toString() method in the superclass and then you need to select the inherited method and select toString() there.

enter image description here

Sneh
  • 3,527
  • 2
  • 19
  • 37
2

Bit late, but consider using the reflectionToString method in the ToStringBuilder class in the Apache Commons library rather than implementing your own toString method for each class. You can use it like this:

public String toString() {
    ToStringBuilder.reflectionToString(this)
}

It'll dynamically generate a String based on all the fields in your class, including those in any superclasses.

You can also tune the output a bit if you want different behaviour for some cases (excluding some fields, not including inherited fields etc).

rcgeorge23
  • 3,594
  • 4
  • 29
  • 54
1

I know this is slightly off-topic, but someone might prefer the following code:

public String toString() {
   StringBuilder toReturn = new StringBuilder("\r\n-------------\r\n");
   Class<?> c = this.getClass();
   toReturn.append(c.getName()).append("\r\n");
   Method[] methods = c.getMethods();
   for (Method method : methods) {
     if (method.getName().startsWith("get") && !method.getName().equals("getClass")) {
       Object obj = new String("no value");
       try {
         obj = method.invoke(this, (Object[]) null);
       } catch (Throwable e) {
       }
       toReturn.append(method.getName()).append(" -> ").append(obj).append("\r\n");
     }
   }
   toReturn.append("-------------\r\n");
   return toReturn.toString();

}

Aram Paronikyan
  • 1,598
  • 17
  • 22