3
package a;
public class A {
  public String toString() {
    // return "I am an a.A"; is too primitive ;) 
    return "I am an " + getClass().getName(); // should give "a.A"
  }
}

--

package a;
public class X extends A {
  public static void main(String[] args) {
    X test = new X();
    System.out.println(test);  // returns "I am an a.X"
  }
}

I also tried with this.getClass() and super.getClass(). How can I get the class name of where toString() and getClass() is coded actually ? (a.A)

This is just a simplified sample, my point is how to avoid hard coding the base class name in the first file (A.java)

datafiddler
  • 1,755
  • 3
  • 17
  • 30

3 Answers3

5
package a;
public class A {
  public String toString() {
    return "I am an " + A.class.getName();
  }
}

should do the trick.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

just iterate over all super

public String toString() {
  Class cl = getClass();
  while (cl.getSuperclass() != Object.class) 
    cl = cl.getSuperclass();
  return cl.getName();
}
rustot
  • 331
  • 1
  • 11
1

Change :

getClass().getName()

into

A.class.getName()
Nyakiba
  • 862
  • 8
  • 18
  • `this.class` wont do - "A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the token class. It evaluates to an object of type Class, the class object for the named type (or for void). " – Gyro Gearless Nov 02 '16 at 12:40