0

I constantly catch NoSuchMethodException TypesForSets$SetType.<init>(int) during attempts to reach out the constructor of the nested class. I have code:

    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;
            }
         }
    }

When I put SetType separately as public class it works just fine.

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192

1 Answers1

3

From what you're doing, it looks as though you want to declare SetType as static.

As things stand, you're trying to instantiate SetType from a static method of TypesForSets; that is, you're doing it outside any instance of TypesForSets. You can't instantiate a non-static inner class except from an instance of the enclosing class.

The reason that it works if you make SetType a separate class in its own file is that it then doesn't have an enclosing class. A static class declared inside another class works much like a top-level class.

It is possible to use reflection to instantiate an inner (non-static) class, and that is covered in this question, but it doesn't look as though that's what you need for your code.

Community
  • 1
  • 1
chiastic-security
  • 20,430
  • 4
  • 39
  • 67