Java - getConstructor()?

msr*_*msr 4 java reflection getconstructor

我把这个问题写成代码中的注释,我觉得这样比较容易理解.

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{
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

提前致谢!

Osc*_*Ryz 5

首先,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 
      }
}
Run Code Online (Sandbox Code Playgroud)

后来......

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();
    }
}
Run Code Online (Sandbox Code Playgroud)