Close

Java Reflection - Class.getDeclaredField() Examples

Code Snippets 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 getDeclaredField(String name)
                       throws NoSuchFieldException, SecurityException

This method returns the Field object for the specified field name declared in this class. It does not return fields declared in super classes.

Parameters:
name - the name of the field
Returns:
the Field object for the specified field in this class


Examples


package com.logicbig.example.clazz;

import java.lang.reflect.Field;

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

public static void main(String... args) throws NoSuchFieldException {
Class<GetDeclaredFieldExample> c = GetDeclaredFieldExample.class;
Field field = c.getDeclaredField("i");
System.out.println(field);

field = c.getDeclaredField("s");
System.out.println(field);
}


}

Output

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




package com.logicbig.example.clazz;

import java.lang.reflect.Field;

public class GetDeclaredFieldExample2 {

public static void main(String... args) throws NoSuchFieldException {
Class<MyClass> c = MyClass.class;
Field field = c.getField("i");
System.out.println(field);
}

static class MyClass {
}

static class SupClass {
public int i;
}
}

Output

Caused by: java.lang.NoSuchFieldException: i
at java.base/java.lang.Class.getField(Class.java:1956)
at com.logicbig.example.clazz.GetDeclaredFieldExample2.main(GetDeclaredFieldExample2.java:15)
... 6 more




See Also