Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - getConstructor()?

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!

like image 817
rasgo Avatar asked Feb 27 '23 03:02

rasgo


2 Answers

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();
    }
}
like image 182
OscarRyz Avatar answered Mar 05 '23 17:03

OscarRyz


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.

like image 29
BalusC Avatar answered Mar 05 '23 17:03

BalusC