嵌套反射 类

Reflection in nested classes

在尝试访问嵌套 class 的构造函数时,我经常遇到 NoSuchMethodException TypesForSets$SetType.<init>(int)。我有代码:

    public class TypesForSets {
        static <T> Set<T> fill(Set<T> set, Class<T> type) {
            try {
                for (int i = 0; i < 10; i++)
                    set.add(type.getConstructor(int.class).newInstance(i));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return set;
        }

         static <T> void test(Set<T> set, Class<T> type) {
                fill(set, type);
         }

         public static void main(String[] args) {
                test(new HashSet<SetType>(), SetType.class);
         }

         class SetType {
            int i;

            public SetType(int n) {
                i = n;
            }
         }
    }

当我将 SetType 单独放置为 public class 时,它工作得很好。

从您的操作来看,您似乎想将 SetType 声明为 static

就目前而言,您正在尝试从 TypesForSetsstatic 方法实例化 SetType;也就是说,您是在 TypesForSets 的任何实例之外进行操作。您不能实例化非静态内部 class ,除非是封闭 class.

的实例

如果您在其自己的文件中将 SetType 设为单独的 class,它会起作用的原因是它没有封闭的 class。在另一个 class 中声明的静态 class 与顶级 class.

非常相似

可以使用反射来实例化内部(非静态)class,这在 this question 中有所介绍,但看起来这并不是您所需要的你的代码。