开发者

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

开发者 https://www.devze.com 2023-03-26 03:39 出处:网络
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

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 myMethods 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消