从 String 获取 Class 类型

我有一个 String,它有一个类的名称说 "Ex"(没有 .class扩展)。我想把它赋给一个 Class变量,像这样:

Class cls = (string).class

我该怎么做?

153896 次浏览
Class<?> cls = Class.forName(className);

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

It should be:

Class.forName(String classname)

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();
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.

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

public static Class<?> getType(String typeName) {
if(typeName.equals("Date")) {
return Date.class;
} else if(typeName.equals("Float")) {
return Float.class;
} else if(typeName.equals("Double")) {
return Double.class;
} else if(typeName.equals("Integer")) {
return Integer.class;
}
return String.class;
}