class.forname().newinstance()
时间: 2023-10-04 22:06:35 浏览: 52
This code creates a new instance of a class using reflection in Java.
`Class.forName()` returns a Class object for the class with the specified name.
`.newInstance()` creates a new instance of the class represented by the Class object returned by `Class.forName()`.
Together, `Class.forName().newInstance()` creates a new instance of the class with the specified name.
Note: This method has been deprecated in Java 9 and replaced with `Class.newInstance()` which throws a more specific exception.
相关问题
class.forname(str).newinstance
class.forName(str).newInstance是Java中的反射机制,可以根据类的全限定名(即包名+类名)动态创建一个对象实例。其中,class.forName(str)是获取该类的Class对象,newInstance()则是通过该Class对象创建一个新的实例。
class.forname怎么用
`Class.forName()` 是 Java 中的反射机制。它用于获取指定类名的 Class 对象。可以通过以下步骤使用 `Class.forName()`:
1. 导入 java.lang.Class 类。
2. 使用 `Class.forName()` 方法获取指定类名的 Class 对象。例如,以下代码将获取名为 `MyClass` 的类的 Class 对象:
```java
Class<?> myClass = Class.forName("MyClass");
```
注意,如果指定的类名在类路径上不可用,`Class.forName()` 方法将抛出 `ClassNotFoundException` 异常。
3. 可以使用获取的 Class 对象进行反射操作,例如创建新实例、访问字段和方法等。
```java
// 创建新实例
Object myObj = myClass.newInstance();
// 获取字段名为 myField 的字段值
Field myField = myClass.getDeclaredField("myField");
myField.setAccessible(true);
Object fieldValue = myField.get(myObj);
// 调用名为 myMethod 的方法
Method myMethod = myClass.getDeclaredMethod("myMethod");
myMethod.invoke(myObj);
```
注意,使用反射操作需要处理可能抛出的异常,例如 `NoSuchFieldException`、`IllegalAccessException` 和 `InvocationTargetException` 等。