开发者

How to get an instance of my object's parent

Is there a way in Java to get an instance of my object's parent class from that object?

ex.

public class Foo extends Bar {

     public Bar g开发者_StackOverflow中文版etBar(){
          // code to return an instance of Bar whose members have the same state as Foo's
     }

}


There's no built-in way to do this. You can certainly write a method that will take a Foo and create a Bar that's been initialized with the relevant properties.

  public Bar getBar() {
       Bar bar = new Bar();
       bar.setPropOne(this.getPropOne());
       bar.setPropTwo(this.getPropTwo());
       return bar;
  }

On the other hand, what inheritance means is that a Foo is a Bar, so you could just do

 public Bar getBar() {
      return this;
   }


Long story short:

return this;

If you want to return a copy, then create a copy constructor on Bar that receives another Bar.

public Bar(Bar that) {
    this.a = that.a;
    this.b = that.b;
    ...
}


this this is an instance of bar, the simple thing is just "return this;" but if you need a distinct object, perhaps you could implement java.lang.Clonable and "return this.clone();"


If your class extends Bar, it is an instance of Bar itself. So

public Bar getBar() {
  return (Bar) this;
}

should do it. If you want a "different instance", you can try:

public Bar getBar() {
   return (Bar) this.clone();
}


Since Foo is-a Bar, you can do this:

return this;

This will only return the parent instance of current object.


You can use reflection

    package com;

    class Bar {

        public void whoAreYou(){
            System.out.println("I'm Bar");
        }

    }

    public class Foo extends Bar{

        public void whoAreYou() {
            System.out.println("I'm Foo");
        }

        public Bar getBar() {
            try {
                return (Bar)this.getClass().getSuperclass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            throw new RuntimeException();
        }

        public static void main() {
            Foo foo = new Foo();
            foo.whoAreYou();
            foo.getBar().whoAreYou();
        }
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜