4

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

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{
}

有什么建议么?

提前致谢!

4

2 回答 2

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 
      }
}

之后 ...

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-24T00:11:01.990 回答
3

如果该类具有(隐式)默认无参数构造函数,那么您只需调用Class#newInstance(). 如果要获取特定的构造函数,请使用Class#getConstructor()其中将参数类型传递给然后调用Constructor#newInstance()它。蓝色的代码实际上是链接,单击它们以获取 Javadoc,其中包含有关该方法的具体作用的详细说明。

要了解有关反射的更多信息,请参阅有关该主题的 Sun 教程

于 2010-04-23T23:59:20.387 回答