0

I have an abstract class and i am wondering if it is possible to know the instance of that class inside one of its methods.

I mean if there's any way to get it. Like some java method like myClass.whereAmI() or something like that.

For example:

public abstract class MyClass {

    public void myMethod(String string){

        String instance = MyClass.getClass(); //I want to get the type of the instance.
        ....

    }
}

Is this possible?

Paplusc
  • 1,080
  • 1
  • 12
  • 24
  • 2
    have you tried this.getClass() ? – Afgan Apr 01 '19 at 07:42
  • 1
    Yes, you can, however any design which relies on this behaviour is usually bad. – Michael Apr 01 '19 at 07:43
  • 1
    The point is: a *base* class should **not at all** know about specific sub classes. By asking "what subclass is running this method" you basically make the base dependent on the child class, and that is *always* wrong. – GhostCat Apr 01 '19 at 07:47
  • Okay i understand, you are right, i think i am gonna get that instance before i call the method. Thank you very much. – Paplusc Apr 01 '19 at 07:49

1 Answers1

2

Just use the getClass() instance method inherited from java.lang.Object:

public void myMethod(String string) {
    Class<?> instanceClass = getClass();
    String instanceClassName = instanceClass.getName();
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thank you, it does the job, but i am going to avoid doing this cause of the comment of @GhostCat. Thank you very much! – Paplusc Apr 01 '19 at 07:51