Creating an object based on class name

W

Wes Harrison

Is it possible to create a new instance of a class whose name is in a String
variable? If so, could you please show me how it's done?

Thanks,

Wes
 
J

Joona I Palaste

Wes Harrison said:
Is it possible to create a new instance of a class whose name is in a String
variable? If so, could you please show me how it's done?

Look up java.lang.Class.forName() and java.lang.Class.newInstance().
Also remember that if you are trying to cast it into a type whose name
is in a String variable, or cast it into something a Class object
represents, you're on the wrong track. As quite explicitly stated
elsewhere on this newsgroup, variable type casting in Java happens
completely statically.
 
F

F

Wes Harrison said:
Is it possible to create a new instance of a class whose name is in a String
variable? If so, could you please show me how it's done?

Thanks,

Wes
String className="java.util.Sting";
String s=(String)(Class.forName(className)).newInstance();


f.
 
J

Joona I Palaste

F said:
String className="java.util.Sting";
String s=(String)(Class.forName(className)).newInstance();

java.lang.String is a final class and thus it is impossible for a
class called java.util.Sting to extend it. Therefore the second line
will throw a ClassCastException.
 
B

Bryce

Is it possible to create a new instance of a class whose name is in a String
variable? If so, could you please show me how it's done?

If you want to instantiate a class, and know it has a default
constructor (i.e., no parameters) then:

Class.forName(classNameAsString).newInstance();

Generally, you do this if you know it implements an interface or
abstract class. If you know nothing about the class, then you wouldn't
know what methods to call (although, you could use reflection, but
that would be somewhat random, as you wouldn't know beforehand what to
expect).

If you want to instantiate a class, and know what parameters are
passed in the constructor, you can do that as well.

Check out here:
http://javaalmanac.com/egs/java.lang.reflect/Constructors.html
 
C

Christophe Vanfleteren

Joona said:
java.lang.String is a final class and thus it is impossible for a
class called java.util.Sting to extend it. Therefore the second line
will throw a ClassCastException.

I'm pretty sure F meant to say String className="java.lang.String"; instead,
in which case the construct works perfectly.
Nothing to do with extending final classes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top