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.
精彩评论