Instantiate an Inner Class With Reflection in Java – 用 Java 中的 Reflection 实例化内部类

最后修改: 2024年 2月 6日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll discuss instantiating an inner class or a nested class in Java using the Reflection API.

在本教程中,我们将讨论使用 Reflection API 在 Java 中实例化 内层类或嵌套类

Reflection API is particularly important in scenarios where the structure of Java classes is to be read and the classes instantiated dynamically. Particular scenarios are scanning annotations, finding and instantiating Java beans with the bean name, and many more. Some popular libraries like Spring and Hibernate and code analysis tools use it extensively.

Reflection API 在需要读取 Java 类的结构并动态实例化类的应用场景中尤为重要。具体应用场景包括扫描注解、使用 bean 名称查找和实例化 Java Bean 等等。一些流行的库,如 Spring 和 Hibernate 以及代码分析工具都广泛使用注释。

Instantiating inner classes poses challenges in contrast to normal classes. Let’s explore more.

与普通类相比,内部类的实例化带来了挑战。让我们进一步探讨。

2. Inner Class Compilation

2.内部类编译

To use Java Reflection API on an inner class, we must understand how the compiler treats it. So, as an example let’s first define a Person class that we’ll use for demonstrating the instantiation of an inner class:

要在内部类中使用 Java Reflection API,我们必须了解编译器是如何处理它的。因此,作为示例,让我们首先定义一个 Person 类,用于演示内部类的实例化:

public class Person {
    String name;
    Address address;

    public Person() {
    }

    public class Address {
        String zip;

        public Address(String zip) {
            this.zip = zip;
        }
    }

    public static class Builder {
    }
}

The Person class has two inner classes, Address and Builder. The Address class is non-static because, in the real world, address is mostly tied to an instance of a person. However, Builder is static because it’s needed to create the instance of the Person. Hence, it must exist before we can instantiate the Person class.

Person 类有两个内部类,即 AddressBuilderAddress 类是非静态的,因为在现实世界中,地址大多与一个人的实例相关联。但是,Builder 是静态的,因为需要它来创建 Person 的实例。因此,在我们实例化 Person 类之前,它必须存在。

The compiler creates separate class files for the inner classes instead of embedding them into the outer class. In this case, we see that the compiler created three classes in total:

编译器会为内部类创建单独的类文件,而不是将它们嵌入到外部类中。在本例中,我们看到编译器总共创建了三个类:

inner class compilation

The compiler generated the Person class and interestingly it also created two inner classes with names Person$Address and Person$Builder.

编译器生成了 Person 类,有趣的是,它还创建了两个内部类,名称分别为 Person$AddressPerson$Builder

The next step is to find out about the constructors in the inner classes:

下一步是找出内部类中的构造函数:

@Test
void givenInnerClass_whenUseReflection_thenShowConstructors() {
    final String personBuilderClassName = "com.baeldung.reflection.innerclass.Person$Builder";
    final String personAddressClassName = "com.baeldung.reflection.innerclass.Person$Address";
    assertDoesNotThrow(() -> logConstructors(Class.forName(personAddressClassName)));
    assertDoesNotThrow(() -> logConstructors(Class.forName(personBuilderClassName)));
}

static void logConstructors(Class<?> clazz) {
    Arrays.stream(clazz.getDeclaredConstructors())
      .map(c -> formatConstructorSignature(c))
      .forEach(logger::info);
}

static String formatConstructorSignature(Constructor<?> constructor) {
    String params = Arrays.stream(constructor.getParameters())
      .map(parameter -> parameter.getType().getSimpleName() + " " + parameter.getName())
      .collect(Collectors.joining(", "));
    return constructor.getName() + "(" + params + ")";
}

Class.forName() takes in the fully qualified name of the inner class and returns the Class object. Further, with this Class object, we get the details of the constructor using the method logConstructors():

Class.forName()接收内部类的全称,并返回 Class 对象。此外,有了这个 Class 对象,我们就可以使用方法 logConstructors() 获取构造函数的详细信息:

com.baeldung.reflection.innerclass.Person$Address(Person this$0, String zip)
com.baeldung.reflection.innerclass.Person$Builder()

Surprisingly, in the constructor of the non-static Person$Address class, the compiler injects this$0 holding the reference to the enclosing Person class as the first argument. But the static class Person$Builder has no reference to the outer class in the constructor.

令人惊讶的是,在非静态 Person$Address 类的构造函数中,编译器注入了 this$0 作为第一个参数,其中包含对外层 Person 类的引用。但是静态类 Person$Builder 在构造函数中没有对外部类的引用。

We’ll keep this behavior of the Java compiler in mind while instantiating the inner classes.

在实例化内部类时,我们将牢记 Java 编译器的这一行为。

3. Instantiate a Static Inner Class

3.实例化静态内部类

Instantiating a static inner class is almost similar to instantiating any normal class by using the method Class.forName(String className):

通过使用方法 Class.forName(String className),创建静态内部类几乎与实例化任何普通类相似:

@Test
void givenStaticInnerClass_whenUseReflection_thenInstantiate()
    throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
      InstantiationException, IllegalAccessException {
    final String personBuilderClassName = "com.baeldung.reflection.innerclass.Person$Builder";
    Class<Person.Builder> personBuilderClass = (Class<Person.Builder>) Class.forName(personBuilderClassName);
    Person.Builder personBuilderObj = personBuilderClass.getDeclaredConstructor().newInstance();
    assertTrue(personBuilderObj instanceof Person.Builder);
}

We passed the fully qualified name “com.baeldung.reflection.innerclass.Person$Builder” of the inner class to Class.forName(). Then we called the newInstance() method on the constructor of the Person.Builder class to get personBuilderObj.

我们将内部类的全限定名 “com.baeldung.reflection.innerclass.Person$Builder” 传递给 Class.forName(). 然后,我们调用了 Person.Builder 类构造函数上的newInstance()方法,以获取 personBuilderObj.

4. Instantiate a Non-Static Inner Class

4.实例化一个非静态内部类

As we saw before, the Java compiler injects the reference to the enclosing class as the first parameter to the constructor of the non-static inner class.

正如我们之前看到的, Java 编译器会将外层类的引用作为第一个参数注入到非静态内部类的构造函数中。

With this knowledge, let’s try instantiating the Person.Address class:

有了这些知识,让我们尝试实例化 Person.Address 类:

@Test
void givenNonStaticInnerClass_whenUseReflection_thenInstantiate()
    throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
      InstantiationException, IllegalAccessException {
    final String personClassName = "com.baeldung.reflection.innerclass.Person";
    final String personAddressClassName = "com.baeldung.reflection.innerclass.Person$Address";

    Class<Person> personClass = (Class<Person>) Class.forName(personClassName);
    Person personObj = personClass.getConstructor().newInstance();

    Class<Person.Address> personAddressClass = (Class<Person.Address>) Class.forName(personAddressClassName);

    assertThrows(NoSuchMethodException.class, () -> personAddressClass.getDeclaredConstructor(String.class));
    
    Constructor<Person.Address> constructorOfPersonAddress = personAddressClass.getDeclaredConstructor(Person.class, String.class);
    Person.Address personAddressObj = constructorOfPersonAddress.newInstance(personObj, "751003");
    assertTrue(personAddressObj instanceof Person.Address);
}

First, we created the Person object. Then, we passed the fully qualified name “com.baeldung.reflection.innerclass.Person$Address” of the inner class to Class.forName(). Next, we got the constructor Address(Person this$0, String zip) from personAddressClass.

首先,我们创建了 Person 对象。然后,我们将内部类的全限定名 “com.baeldung.reflection.innerclass.Person$Address” 传递给 Class.forName()。接下来,我们从 personAddressClass 获得了构造函数 Address(Person this$0, String zip)

Finally, we called the newInstance() method on the constructor with the personObj and zip 751003 parameters to get personAddressObj.

最后,我们使用 personObjzip 751003 参数调用了构造函数上的 newInstance() 方法,以获得 personAddressObj

We also see that the method personAddressClass.getDeclaredConstructor(String.class) throws NoSuchMethodException because of the missing first argument this$0.

我们还看到,方法 personAddressClass.getDeclaredConstructor(String.class) 引发了 NoSuchMethodException 异常,原因是缺少第一个参数 this$0

5. Conclusion

5.结论

In this article, we discussed the Java Reflection API to instantiate static and non-static inner classes. We found that the compiler treats the inner classes as an external class instead of an embedded class in the outer class.

在本文中,我们讨论了用于实例化静态和非静态内部类的 Java Reflection API。我们发现,编译器会将内部类视为外部类,而不是外层类中的嵌入类。

Also, the constructors of the non-static inner class by default take an outer class object as the first argument. However, we can instantiate the static classes similar to any normal class.

此外,非静态内部类的构造函数默认将外部类对象作为第一个参数。不过,我们可以像其他普通类一样实例化静态类。

As usual, the code used can be found over on GitHub.

像往常一样,使用的代码可以在 GitHub 上找到