views:

100

answers:

4

I have a string with the name of a class, is there a way (writing in Java) to use that string when creating a new instance of that class, to do something like this:
object obj = new dataInString.
So the dataInString is parsed from the string.

A: 

Use reflections to instantiate objects. A simple class.forName("com.blah.blah") should be a good starting point to look for more information on reflections.

Ritesh M Nayak
+3  A: 

You can use reflection.

fastcodejava
Thanks, that is the direction I need.
Xenorose
Glad to be of help.
fastcodejava
+4  A: 

Do you mean something like Class.forName(String)? Quoting the javadoc of the method:

Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to:

Class.forName(className, true, currentLoader)

where currentLoader denotes the defining class loader of the current class.

For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread:

Class t = Class.forName("java.lang.Thread")

A call to forName("X") causes the class named X to be initialized.

And then, call Class#newInstance() on the returned Class (it must have an empty constructor).

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

Pascal Thivent
+4  A: 

Assuming that the class has a no-args constructor, then the following should do the trick

Class<?> clazz = Class.forName("someclass");
Object obj = clazz.newInstance();

If you need to create the object using a different constructor, then you will need to do something like this:

Constructor<?> ctor = clazz.getConstructor(ArgClass.class, Integer.TYPE);
Object obj = ctor.newInstance(arg, Integer.valueOf(42));

There are a number of checked exceptions that need to be handled in either case ...

Stephen C
I think, you meant Integer.TYPE instead of Integer.CLASS. Also, I would recommend against the new Integer(...) if using Java 1.5 or higher (since you are using varargs, that would be the case): Either rely on autoboxing or use Integer.valueOf(...) - this avoids creating new objects for commonly used instances.
nd
Thanks .... fixed
Stephen C