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.
views:
100answers:
4Use reflections to instantiate objects. A simple class.forName("com.blah.blah") should be a good starting point to look for more information on reflections.
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 namedjava.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 anew
expression with an empty argument list. The class is initialized if it has not already been initialized.
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 ...