Ankur
Ankur

Reputation: 51110

Can a method know the type of Object that is calling it (i.e. the subtype that is calling it)

This relates to the Java language.

Let's say I have we have a super class A and subclasses X and Y. I have a method in A that needs to know the type of X and Y (it's an external library).

I have a method on A called someMethod(). My question is: in the someMethod() implementation is there a way to find out whether it is being called by X or Y?

Please let me know if this is not clear.

EDIT^2:

The concrete situation in class A looks like this.

public void delete() {
    Datastore ds = Dao.instance().getDatabase();
    ds.delete(this.getClass(),this.id);
}

and I'd like to be able to do X.delete() and Y.delete()

Upvotes: 0

Views: 67

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502496

You can easily find out whether the method is called on an X or Y, using getClass():

public void someMethod() {
    System.out.println(getClass()); // Will display the execution-time type
}

But of course that public method could be called by any class (not just X or Y). If you need to get that information, you'll need to get the stack trace - which may not always be reliable due to inlining etc. The right course of action will depend on why you want this information.

Upvotes: 3

NPE
NPE

Reputation: 500733

Yes: simply call getClass(). For example:

class A {
  public void someMethod() {
    System.out.println(getClass().getSimpleName());
  }
}

This would print out either X or Y depending on the runtime class of the object on which it is invoked.

Upvotes: 3

Related Questions