Domanda

I have a 5 classes they all extend a BaseClass. If in my base class a method is being executed I would like to know which of the 5 classes called that method in my base class. I don't think I am able to pass a variable in my super call. It is an android project and the call is kind of predefined. I thought rather in my BaseClass I can call something like "getCallingClass" or something like this.

Anyone an idea?

È stato utile?

Soluzione

you can do this.getClass(); to get the class of the calling object.

you can get the class name by this.getClass().getName().

Or else you can use instanceof operator to check which class the calling object belongs to.

So in your base class function you can simply check:

if(this instanceof ClassA){

}

Altri suggerimenti

A superclass's method shouldn't be relying on information such as which subclass is calling it. If you are going to do something based on which subclass called it, then that logic should be in the subclass, not in the superclass.

Override the method in the subclass, calling the superclass method explicitly, then add your own subclass-specific logic.

Superclass:

public void aMethod() {
    // do superclass logic here.
}

Subclass:

@Override
public void aMethod() {
    super.aMethod();
    // Subclass-specific logic goes in the overriding method.
}

Normally in the base class you should not need to know
which subclass is executing/calling the current method.
If you need to know that, then you're doing something not
quite right, and you should think why you need to know it.

All five children of your base class inherit their own version of their parent's methods, excluding private methods or constructors. If class Foo extends class Bar, then every non-private method in Bar is also in Foo.

Calling this.getClass(); will give you the whatever class you are currently inside of. If you call it inside of Foo, you'll get Foo. If you call it inside of Bar, you'll get Bar. If Foo inherits a method that lives in Bar, you'll still be a Foo inside of that method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top