How to get the parent base class object super.getClass()

后端 未结 5 594
夕颜
夕颜 2020-11-27 07:09

I have a little problem with Java (being a C++ programmer).

I have 2 related classes:

public class Patient() {
...
}

public class PatientPersistent          


        
相关标签:
5条回答
  • 2020-11-27 07:41

    Object.getClass() returns the runtime type of an object, so prepending super to the call doesn't really do much.

    You could use getClass().getSuperclass().

    0 讨论(0)
  • 2020-11-27 07:44
    getClass().getSuperclass()
    

    But don't use this. It is certainly a sign of bad design.

    0 讨论(0)
  • 2020-11-27 07:54

    I find a lot of time that solving a problem with "magic" in the way you are suggesting leads to a solution that is not very flexible.

    If you are trying to get your super's class, what you probably want is to be calling a method in your parent's class that explicitly implements whatever action you were going to take after you looked up the parent's type.

    Furthermore, there is a good chance that the design would be better yet if the method you were currently implementing were actually IN your parent class and that method was referring to an abstract method implemented in the child class--flipping your design on its head.

    Of course I'm inferring this all from your desire to get the parent type and may be totally wrong, but I do think that if knowing your parent's class is the answer you're looking for then you are asking the wrong question--back up a few feet and look again.

    0 讨论(0)
  • 2020-11-27 07:57

    Nice... super.getClass() is actually Object's getClass(), which returns the runtime type of the instance it is invoked on (this in this case). Therefore you receive the same class...

    Instead of asking for the runtime class of this using the super's implementation, You should ask for the super class of the class returned by getClass:

    getClass().getSuperclass()
    

    And by the way, what do you mean by "This will allow me to generalize some methods which I need to implement in each child which is awful."? Are you sure you have no other design choice?

    0 讨论(0)
  • 2020-11-27 07:58

    Try: getClass().getSuperclass().toString()

    0 讨论(0)
提交回复
热议问题