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?
This question is related to
java
class
reflection
Not sure what you are asking, but... Class.forname, maybe?
You can use the forName
method of Class
:
Class cls = Class.forName(clsName);
Object obj = cls.newInstance();
You can get the Class reference of any class during run time through the Java Reflection Concept.
Check the Below Code. Explanation is given below
Here is one example that uses returned Class to create an instance of AClass:
package com.xyzws;
class AClass {
public AClass() {
System.out.println("AClass's Constructor");
}
static {
System.out.println("static block in AClass");
}
}
public class Program {
public static void main(String[] args) {
try {
System.out.println("The first time calls forName:");
Class c = Class.forName("com.xyzws.AClass");
AClass a = (AClass)c.newInstance();
System.out.println("The second time calls forName:");
Class c1 = Class.forName("com.xyzws.AClass");
} catch (ClassNotFoundException e) {
// ...
} catch (InstantiationException e) {
// ...
} catch (IllegalAccessException e) {
// ...
}
}
}
The printed output is
The first time calls forName:
static block in AClass
AClass's Constructor
The second time calls forName:
The class has already been loaded so there is no second "static block in AClass"
The Explanation is below
Class.ForName is called to get a Class Object
By Using the Class Object we are creating the new instance of the Class.
Any doubts about this let me know
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.
It should be:
Class.forName(String classname)
Source: Stackoverflow.com