首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java - getConstructor()?

Java - getConstructor()?
EN

Stack Overflow用户
提问于 2010-04-24 07:53:09
回答 2查看 6.2K关注 0票数 4

我把这个问题写成代码中的注释,我认为这样更容易理解。

代码语言:javascript
复制
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{
}

有什么建议吗?

提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-04-24 08:11:02

首先,BalusC是对的。

其次:

如果你是基于类类型来做决定的,你就不会让多态性来完成它的工作。

您的类结构可能是错误的(比如Car和Person不应该在同一层次结构中)

您可能会创建一个接口和代码。

代码语言:javascript
复制
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 
      }
}

稍后..。

代码语言:javascript
复制
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();
    }
}
票数 5
EN

Stack Overflow用户

发布于 2010-04-24 07:59:20

如果这个类有一个(隐式的)默认的无参数构造函数,那么你可以直接调用Class#newInstance()。如果你想获得一个特定的构造函数,那么使用Class#getConstructor(),在这个函数中,你将参数类型传递给,然后在它上面调用Constructor#newInstance()。蓝色的代码实际上是链接,单击它们可以获得Javadoc,它包含了关于该方法到底做了什么的详细解释。

要了解有关反射的更多信息,请访问Sun tutorial on the subject

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2702624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档