简体   繁体   English

当一个对象作为类型超类传入时,有没有办法检索子类的类型?

[英]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? SuperClass有三个子类, myMethod是否有任何方法可以获取传入的子类的类名?

Not sure if it's important, but SuperClass is abstract. 不确定它是否重要,但SuperClass是抽象的。

is there any way within myMethod I can get the class name of the subclass which was passed in? myMethod中是否有任何方法可以获取传入的子类的类名?

Yes, by using the getClass method : 是的,通过使用getClass方法

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

Remark 1: 备注1:

This does however sound to me like a Bad Design™. 然而,这听起来像是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: 无论你想在做myMethod考虑有在它的方法SuperClass (提供一个有意义的默认实现,或使其抽象迫使子类实现的方法),并调用此方法s在你的方法:

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

Remark 2: 备注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. 如果myMethod的逻辑看起来与SuperClass的目的无关,并且您不想将myMethod代码放在此类中,请考虑实现访问者模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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