- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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()); }