我把这个问题写成代码中的注释,我认为这样更容易理解。
public class Xpto{
protected AbstractClass x;
public void foo(){
// AbstractClass y = new ????? Car or Person ?????
/* here I need a new object of this.x's type (which could be Car or Person)
I know that with x.getClass() I get the x's Class (which will be Car or
Person), however Im wondering how can I get and USE it's contructor */
// ... more operations (which depend on y's type)
}
}
public abstract class AbstractClass {
}
public class Car extends AbstractClass{
}
public class Person extends AbstractClass{
}有什么建议吗?
提前感谢!
发布于 2010-04-24 08:11:02
首先,BalusC是对的。
其次:
如果你是基于类类型来做决定的,你就不会让多态性来完成它的工作。
您的类结构可能是错误的(比如Car和Person不应该在同一层次结构中)
您可能会创建一个接口和代码。
interface Fooable {
Fooable createInstance();
void doFoo();
void doBar();
}
class Car implements Fooable {
public Fooable createInstance() {
return new Car();
}
public void doFoo(){
out.println("Brroooom, brooooom");
}
public void doBar() {
out.println("Schreeeeeeeekkkkkt");
}
}
class Person implements Fooable {
public Fooable createInstance(){
return new Person();
}
public void foo() {
out.println("ehem, good morning sir");
}
public void bar() {
out.println("Among the nations as among the individuals, the respect for the other rights means peace..");// sort of
}
}稍后..。
public class Xpto{
protected Fooable x;
public void foo(){
Fooable y = x.createInstance();
// no more operations that depend on y's type.
// let polymorphism take charge.
y.foo();
x.bar();
}
}发布于 2010-04-24 07:59:20
如果这个类有一个(隐式的)默认的无参数构造函数,那么你可以直接调用Class#newInstance()。如果你想获得一个特定的构造函数,那么使用Class#getConstructor(),在这个函数中,你将参数类型传递给,然后在它上面调用Constructor#newInstance()。蓝色的代码实际上是链接,单击它们可以获得Javadoc,它包含了关于该方法到底做了什么的详细解释。
要了解有关反射的更多信息,请访问Sun tutorial on the subject。
https://stackoverflow.com/questions/2702624
复制相似问题