我有一个带有类名称的字符串,有没有一种方法(用 Java 编写)在创建该类的新实例时使用该字符串来执行如下操作:
object obj = new dataInString。
所以dataInString是从字符串中解析出来的。
最佳答案
你的意思是像Class.forName(String)
?引用方法的javadoc:
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.
然后,调用Class#newInstance()
在返回的 Class
上(它必须有一个空的构造函数)。
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.
关于java - 一种使用字符串创建新类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1960812/