java 如何获取我的对象的父对象的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3909258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an instance of my object's parent
提问by stevebot
Is there a way in Java to get an instance of my object's parent class from that object?
Java 中有没有办法从该对象中获取我的对象的父类的实例?
ex.
前任。
public class Foo extends Bar {
public Bar getBar(){
// code to return an instance of Bar whose members have the same state as Foo's
}
}
回答by Jacob Mattison
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.
没有内置的方法可以做到这一点。您当然可以编写一个方法,该方法将采用 Foo 并创建一个已使用相关属性初始化的 Bar。
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 aBar, so you could just do
另一方面,继承的意思是 Foo是一个Bar,所以你可以这样做
public Bar getBar() {
return this;
}
回答by biasedbit
Long story short:
长话短说:
return this;
If you want to return a copy, then create a copy constructor on Bar that receives another Bar.
如果你想返回一个副本,那么在 Bar 上创建一个复制构造函数来接收另一个 Bar。
public Bar(Bar that) {
this.a = that.a;
this.b = that.b;
...
}
回答by stew
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();"
this this 是 bar 的一个实例,简单的就是“return this;” 但是如果你需要一个不同的对象,也许你可以实现 java.lang.Clonable 并“返回 this.clone();”
回答by krico
If your class extends Bar, it is an instance of Bar itself. So
如果你的类扩展了 Bar,它就是 Bar 本身的一个实例。所以
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();
}
回答by Buhake Sindi
Since Foo is-aBar, you can do this:
由于 Foo is-aBar,你可以这样做:
return this;
This will only return the parent instance of current object.
这只会返回当前对象的父实例。
回答by asela38
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();
}
}