eJm
eJm

Reputation: 147

Instantiating a class, passed in java?

I have a query regarding instantiating a new object in java from a class passed as a parameter in a method, for example:

void myMethod(Class aReceived){
    object = new aReceived       // object will be a superclass of aReceived
}

I have seen this done using objective-C in a couple of lines but am uncertain how it works in java.

can you help?

Thanks in advance ;)

Upvotes: 1

Views: 703

Answers (4)

Itay Maman
Itay Maman

Reputation: 30733

If you want to create an object via the no-arg constructor:

void myMethod(Class<?> aReceived) {
  Object newObject = aReceived.newInstance();
  ...
}

If you want to create an object via a two-arg constructor (taking String, int):

void myMethod(Class<?> aReceived) {
  Object newObject = aReceived.getConstructor(String.class, int.class)
      .newInstance("aaa", 222);
  ...
}

Finally, you can use generics to properly set the type of the newObject variable (on top of either of the above snippets):

void myMethod(Class<T> aReceived) {
  T newObject = aReceived.getConstructor(String.class, int.class)
      .newInstance("aaa", 222);  
  ...
  // Sadly, due to erasure of generics you cannot do newObject.SomeMethodOfT() 
  // because T is effectively erased to Object. You can only invoke the 
  // methods of Object and/or use refelection to dynamically manipulate newObject
}

[Addendum]

How do you call this method?

Option 1 - when you know, in code-writing time, what class you want to pass to the method:

myMethod(TestClass.class)

Option 2 - when the name of the class to be instantiated is known only in runtime, as a string:

String className = ....; // Name of class to be instantiated
myMethod(Class.forName(className));

Upvotes: 5

fyr
fyr

Reputation: 20869

If you have only a default constructor you may do something like this:

aReceived.newInstance();

If you need to pass parameters you can not use this method. But you may manage this while determing which is the right constructor with getConstructor(Class<?> parameterTypes ...)

e.g. if you want to pass a string as only parameter you might do it like this:

Constructor ctor = aReceived.getConstructor(String.class);
object = ctor.newInstance("somestring");

Upvotes: 1

Kris
Kris

Reputation: 14468

object = aReceived.newInstance();

This assumes that the class has a no-arguments constructor.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074959

Class has a method on it called newInstance for creating instances of that class. You might also look into the whole java.lang.reflect package.

Upvotes: 3

Related Questions