- 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 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()); }
- Related Articles
- Get all declared fields from a class in Java
- Get the list of all the declared methods in Java
- Get the list of all the public fields in Java
- Get the list of all the public methods in Java
- Get the declared method by name and parameter type in Java
- Checking all the list of fields for a table in SAP HANA
- Get all fields names in a MongoDB collection?
- How to get the list of all the MongoDB databases using java?
- How to get list of all files/folders from a folder in Java?
- Get the fields of the current Type in C#
- Get all the IDs of the Time Zone in Java
- How to get the list of all databases using JDBC?
- How to get the list of all the commands available in the PowerShell?
- Get all Constructors in Java
- Get number of fields in MySQL table?
