Domanda

ho scritto la questione come un commento nel codice, penso che la sua più facile da capire in questo modo.

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

Qualche suggerimento?

Grazie in anticipo!

È stato utile?

Soluzione

Prima di tutto, BalusC è giusto.

In secondo luogo:

Se sei di adottare decisioni in base al tipo di classe, non stai lasciando che il polimorfismo fare il suo lavoro.

La vostra struttura di classe può essere sbagliato (come auto e persona non dovrebbe essere nella stessa gerarchia)

Si potrebbe forse creare un'interfaccia e il codice ad esso.

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

Più tardi ...

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();
    }
}

Altri suggerimenti

Se la classe ha un (implicito) di default costruttore no-arg, allora si può solo chiamare Class#newInstance() . Se si desidera ottenere un costruttore specifica, quindi utilizzare Class#getConstructor() in cui si passa il parametertypes da e quindi si chiama Constructor#newInstance() su di esso. Il codice in blu sono in realtà i collegamenti, fare clic su di loro per ottenere il Javadoc, contiene spiegazioni dettagliate su cosa esattamente il metodo fa.

Per saperne di più su di riflessione, la testa al Sun tutorial sul soggetto .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top