概述

内部类.png

反射获取内部类

通过Class的getDeclaredClasses来获取

  1. /* Returns an array of {@code Class} objects reflecting all the
  2. * classes and interfaces declared as members of the class represented by
  3. * this {@code Class} object. This includes public, protected, default
  4. * (package) access, and private classes and interfaces declared by the
  5. * class, but excludes inherited classes and interfaces. This method
  6. * returns an array of length 0 if the class declares no classes or
  7. * interfaces as members, or if this {@code Class} object represents a
  8. * primitive type, an array class, or void.
  9. */
  10. @CallerSensitive
  11. public Class<?>[] getDeclaredClasses() throws SecurityException {
  12. checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
  13. return getDeclaredClasses0();
  14. }

Spring抽象封装

ClassMetadata#getMemberClassNames

  1. /**
  2. * Return the names of all classes declared as members of the class represented by
  3. * this ClassMetadata object. This includes public, protected, default (package)
  4. * access, and private classes and interfaces declared by the class, but excludes
  5. * inherited classes and interfaces. An empty array is returned if no member classes
  6. * or interfaces exist.
  7. * @since 3.1
  8. */
  9. String[] getMemberClassNames();

底层实现:StandardClassMetadata#getMemberClassNames

本质上还是反射调用Class的getDeclaredClasses方法。

  1. public String[] getMemberClassNames() {
  2. LinkedHashSet<String> memberClassNames = new LinkedHashSet<>(4);
  3. for (Class<?> nestedClass : this.introspectedClass.getDeclaredClasses()) {
  4. memberClassNames.add(nestedClass.getName());
  5. }
  6. return StringUtils.toStringArray(memberClassNames);
  7. }