java - 一种使用字符串创建新类的方法

标签 java reflection

我有一个带有类名称的字符串,有没有一种方法(用 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 named java.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 a new 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/

相关文章:

java - 将子元素添加到 Selenium 的 html 中后,在页面对象中找不到子元素

java - 如何从 Java 中的字符串获取类引用?

java - 在运行时获取类的泛型类型

c# - 如何在属性参数中进行方法引用

java - 从 ArrayList 中删除重复的字符串

java - 为什么在通过 REST API 调用时枚举并不总是有效?

java - 我得到 java.lang.IndexOutOfBoundsExeption : Invalid index 9, 大小为 5

scala - 反射可以提取特征中使用的初始值吗?

java - Java反射有通用的 "back-end"库吗

java - JUnit 测试 : invoking parent class protected method