views:

104

answers:

6

I have a String which has a name of a class say "Ex" (no .class extension). I want to assign it to a Class variable, like this:

Class cls = (string).class

How can i do that?

+11  A: 
Class<?> cls = Class.forName(className);

But your className should be fully-qualified - i.e. com.mycompany.MyClass

Bozho
muhaha you beat me by 2 secs :)
Hans Westerbeek
its throwing ClassNotFound Exception
Steven
then either the class is not on the classpath or you are not passing the fully qualified class name e.g. com.mycompany.project.ClassName
Hans Westerbeek
what value of `className` are you passing? Is there such a class on your classpath?
Bozho
yeah the Class is in same package
Steven
@Steven - why do you pass as an argument? `MyClassName` or `com.mypackage.MyClassName` ?
Bozho
thanks i got it
Steven
what if class is in different project?
Steven
"project" isn't a term in java-runtime. If you mean "jar" or "archive", then - if the jar is on the classpath, it will work fine.
Bozho
@Steven if you want to run this in an IDE with dependent project, tell us your IDE.
Bozho
+1  A: 

eeh.. Class.forName(String classname) ?

Hans Westerbeek
+1  A: 

Not sure what you are asking, but... Class.forname, maybe?

Manrico Corazzi
its throwing ClassNotFound Exception
Steven
what if class is in different project?
Steven
+3  A: 

You can use the forName method of Class:

                Class cls = Class.forName(clsName);
                Object obj = cls.newInstance();
rsp
+2  A: 
String clsName = "Ex";  // use fully qualified name
Class cls = Class.forName(clsName);
Object clsInstance = (Object) cls.newInstance();

Check the Java Tutorial trail on Reflection at http://java.sun.com/docs/books/tutorial/reflect/TOC.html for further details.

JuanZe
+1  A: 
harigm
what if class is in different project?
Steven
Can you get a jar file of that proect and specify the class namesome thing like Class.forName("oracle.jdbc.driver.OracleDriver")
harigm