siiikooo0743
siiikooo0743

Reputation: 326

Initialize variiable with the type in a variable

public void initialize(Class<? extends MyType> type)
{
   MyType variable = new type();
}

That doesn't work. How can I do it?

-siiikooo

Upvotes: 0

Views: 70

Answers (2)

MineKira
MineKira

Reputation: 21

You can use the newInstance() method of Class object.

for above example you can do:

type.newInstance();

The limitation on for this approach is you can't call constructor that has parameters.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201447

You can call newInstance like this -

public void initialize(Class<? extends MyType> type) {
    try {
        MyType variable = type.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 3

Related Questions