简体   繁体   中英

Is there a way of retrieving the type of a subclass, when an object is passed in as type super class?

If I had a method signature

public void myMethod(SuperClass s){
}

and SuperClass has three subclasses, is there any way within myMethod I can get the class name of the subclass which was passed in?

Not sure if it's important, but SuperClass is abstract.

is there any way within myMethod I can get the class name of the subclass which was passed in?

Yes, by using the getClass method :

public void myMethod(SuperClass s){
    System.out.println(s.getClass());
}

Remark 1:

This does however sound to me like a Bad Design™.

Whatever you want to do in myMethod consider having a method for it in SuperClass (provide a meaningful default implementation, or make it abstract to force subclasses to implement the method) and call this method on s in your method:

public void myMethod(SuperClass s){
    s.abstractMethod();
}

Remark 2:

If myMethod s logic is seemingly unrelated to the purpose of the SuperClass and you don't want to put the myMethod code inside this class, consider implementing the visitor pattern instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM