Question

I wrote the question as a comment in the code, I think its easier to understand this way.

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

Any suggestions?

Thanks in advance!

Was it helpful?

Solution

First of all, BalusC is right.

Secondly:

If you're taking decisions based on the class type, you're not letting the polymorphism do its job.

Your class structure may be wrong ( Like Car and Person should not be in the same hierarchy )

You could probably create an interface and code to it.

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

Later ...

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

OTHER TIPS

If the class has a (implicit) default no-arg constructor, then you can just call Class#newInstance(). If you want to obtain a specific constructor, then use Class#getConstructor() wherein you pass the parametertypes to and then call Constructor#newInstance() on it. The code in blue are actually links, click them to get the Javadoc, it contains detailed explanation about what exactly the method does.

To learn more about reflection, head to the Sun tutorial on the subject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top