Eran
Eran

Reputation: 2424

A way to use a string for creating new classes

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.

Upvotes: 1

Views: 186

Answers (4)

Stephen C
Stephen C

Reputation: 718758

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 ...

Upvotes: 4

Pascal Thivent
Pascal Thivent

Reputation: 570325

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.

Upvotes: 5

fastcodejava
fastcodejava

Reputation: 41087

You can use reflection.

Upvotes: 3

Ritesh M Nayak
Ritesh M Nayak

Reputation: 8043

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.

Upvotes: 0

Related Questions