There is some external and internal class

public class OuterClass { int a = 20; public class InnerClass { String name1="123!!!";}} 

And the implementation in main

 OuterClass obj = new OuterClass(); Class[] classes = obj.getClass().getDeclaredClasses(); for(Class innerClass: classes){ System.out.println(innerClass.getName()); Field[] fields = innerClass.getDeclaredFields(); for(Field field : fields){ System.out.println(field.getName()); try { System.out.println(field.get(innerClass)); //<-----IllegalArgumentException } catch (IllegalAccessException e) { e.printStackTrace(); } } } 

How to get field values ​​of an inner class without making them static?

  • with external class get () works without problems with internal error IllegalArgumentException gets out - Artyom
  • one
    To create an instance of an inner class, you must first create an instance of the outer class. OuterClass.InnerClass obj = obj.new InnerClas (); - Vladimir Glinskikh
  • tutorial - Vladimir Glinskikh

1 answer 1

Since InnerClass is not initialized at the time your code is executed, you can only read field names. If it is necessary to read the default values, we first initialize the inner class:

 public class Outer { int a; public class Inner { String name1 = "123!!!"; } public static void main(String[] args) throws Exception { Outer outer = new Outer(); Class[] classes = outer.getClass().getDeclaredClasses(); for (Class innerClass : classes) { System.out.println(innerClass.getName()); Field[] fields = innerClass.getDeclaredFields(); Constructor constructor = innerClass.getDeclaredConstructor(outer.getClass()); Object innerInstance = constructor.newInstance(outer); for (Field field : fields) { System.out.println(field.getName()); field.setAccessible(true); try { System.out.println(field.get(innerInstance)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } 

Result:

 aug.Outer$Inner name1 123!!! this$0 aug.Outer@29453f44 
  • Thanks, it helped). And the constructor should be called only by hands? - Artyom