

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 all declared fields from a class in Java
An array of field objects is returned by the method java.lang.Class.getDeclaredFields(). 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
package Test; import java.lang.reflect.*; public class Demo { int i; char c; public Demo(int i, char c) { this.i = i; this.c = c; } public static void main(String[] args) { try { Demo obj = new Demo(7, 'A'); Class c = obj.getClass(); Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { System.out.println("The field is: " + fields[i].toString()); } } catch(Exception e) { System.out.println(e.toString()); } } }
Output
The field is: int Test.Demo.i The field is: char Test.Demo.c
Now let us understand the above program.
An object of class Demo is created in the main() method. Then the array fields[] stores the field objects that are obtained using the method getDeclaredFields(). Then the fields are displayed using a for loop. A code snippet which demonstrates this is as follows −
Demo obj = new Demo(7, 'A'); Class c = obj.getClass(); Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { System.out.println("The field is: " + fields[i].toString()); }
- Related Questions & Answers
- Get the list of all declared fields in Java
- Get the list of all the declared methods in Java
- Get all fields names in a MongoDB collection?
- Get the list of all the public fields in Java
- Get all digits from a string in Java
- Get a value from Unit Tuple class in Java
- Get a value from Pair Tuple class in Java
- Get class from an object in Java
- Byte Class Fields in Java with example
- How to get a stream from Optional class in Java 9?
- Get the declared method by name and parameter type in Java
- Get a value from Quartet class in JavaTuples
- Get a value from Triplet class in JavaTuples
- How to retrieve all nested fields from MongoDB collection?
- Get fields from multiple sub-documents that match a condition in MongoDB?