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 に答える