Reputation: 1835
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)
Upvotes: 3
Views: 153
Reputation: 331
just iterate over all super
public String toString() {
Class cl = getClass();
while (cl.getSuperclass() != Object.class)
cl = cl.getSuperclass();
return cl.getName();
}
Upvotes: 1
Reputation: 91149
package a;
public class A {
public String toString() {
return "I am an " + A.class.getName();
}
}
should do the trick.
Upvotes: 5