
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the List of All Declared Fields in Java
The list of all declared fields can be obtained using the java.lang.Class.getDeclaredFields() method as it returns an array of field objects. These field objects include the objects with the public, private, protected and default access but not the inherited fields.
Also, the getDeclaredFields() method returns a zero length array if the class or interface has no declared fields or if a primitive type, array class or void is represented in the Class object.
A program that demonstrates this is given as follows −
Example
import java.lang.reflect.*; public class Demo { public static void main(String[] argv) throws Exception { Class c = java.lang.String.class; Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { System.out.println("The Field is: " + fields[i].toString()); } } }
Output
The Field is: private final char[] java.lang.String.value The Field is: private int java.lang.String.hash The Field is: private static final long java.lang.String.serialVersionUID The Field is: private static final java.io.ObjectStreamField[] java.lang.String.serialPersistentFields The Field is: public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER
Now let us understand the above program.
The class c holds the java.lang.String.class.. Then the array fields[] stores the field objects of this class that are obtained using the method getDeclaredFields(). Then the fields are displayed using the for loop. A code snippet which demonstrates this is as follows −
Class c = java.lang.String.class; Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { System.out.println("The Field is: " + fields[i].toString()); }