Acidic
Acidic

Reputation: 6280

Creating a new instance of the same type as another intsance

I'll try to keep my question simple:

I have the following instance:

MainClass mc = new ExtendingClass()

I want to create a brand new instance using the reference mc. I've read multiple pages online, but found no suitable answer.

One can assume it would look something like this ~ (Perhaps it will help you understand). MyClass mc2 = new mc.getBaseClass()

Basically the outcome should be the same as this:

MyClass mc2 = ExtendingClass() But it would allow me to create mc2 during runtime as it can be an instance of various extending classes.

Thanks in advance.

Upvotes: 0

Views: 52

Answers (1)

Mac
Mac

Reputation: 14791

You could try:

mc.getClass( ).newInstance( );

This of course only works if ExtendingClass has a no-arg or default constructor. If you want to handle arguments to the constructor, it gets a tiny bit more complicated (for example, if you have a constructor that takes a String):

Constructor<ExtendingClass> constructor = mc.getClass( ).getConstructor(String.class);
constructor.newInstance("foo");

Upvotes: 1

Related Questions