Close

Java Reflection - Class.getDeclaredFields() Examples

Java Reflection Java Java API 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public Field[] getDeclaredFields()
                          throws SecurityException

Returns an array of Field objects declared in this class.

Returns:
the array of Field objects representing all the declared fields of this class


Examples


package com.logicbig.example.clazz;

import java.lang.reflect.Field;
import java.util.Arrays;

public class GetDeclaredFieldsExample {
private int i;
private String s;

public static void main(String... args) {
Class<GetDeclaredFieldExample> c = GetDeclaredFieldExample.class;
Field[] fields = c.getDeclaredFields();
Arrays.stream(fields).forEach(System.out::println);
}
}

Output

private int com.logicbig.example.clazz.GetDeclaredFieldExample.i
public java.lang.String com.logicbig.example.clazz.GetDeclaredFieldExample.s




Inner class has an automatic field pointing to the outer class instance (implicitly added during compilation).

See Also: Implicit Outer Class Parameter Tutorial

package com.logicbig.example.clazz;

import java.lang.reflect.Field;

public class GetDeclaredFieldsExample2 {

public static void main(String... args) {
Class<MyClass.MyInnerClass> c = MyClass.MyInnerClass.class;
for (Field field : c.getDeclaredFields()) {
System.out.printf("Field name: %s, type: %s%n",
field.getName(), field.getType().getSimpleName());
}
}

private static class MyClass {
private class MyInnerClass {
int i;
}
}
}

Output

Field name: i, type: int
Field name: this$0, type: MyClass




See Also