datafiddler
datafiddler

Reputation: 1835

how to see the class name containing the actual code

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

Answers (3)

Nyakiba
Nyakiba

Reputation: 862

Change :

getClass().getName()

into

A.class.getName()

Upvotes: 1

rustot
rustot

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

glglgl
glglgl

Reputation: 91149

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

should do the trick.

Upvotes: 5

Related Questions