GetConstructor ()?

I wrote the question as a comment in the code, I think it is easier to understand in 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 type (which could be Car or Person) I know that with x.getClass() I get the x Class (which will be Car or Person), however Im wondering how can I get and USE it contructor */ // ... more operations (which depend on y type) } } public abstract class AbstractClass { } public class Car extends AbstractClass{ } public class Person extends AbstractClass{ } 

Any suggestions?

Thanks in advance!

+4
source share
2 answers

First of all, BalusC is right.

Secondly:

If you make decisions based on the type of class, you do not allow polymorphism to do its job.

Your class structure may be incorrect (for example, Car and Person should not be in the same hierarchy)

Perhaps you can create an interface and code for 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 type. // let polymorphism take charge. y.foo(); x.bar(); } } 
+5
source

If the class has a default (implicit) no-arg constructor, you can simply call Class#newInstance() . If you want to get a specific constructor, use Class#getConstructor() , in which you pass parameter types and then call Constructor#newInstance() . The links are blue, click them to get the Javadoc, it contains a detailed explanation of exactly what this method does.

To learn more about reflection, go to the Sun tutorial on this .

+3
source

Source: https://habr.com/ru/post/1307845/


All Articles