Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
java.lang.reflect.Constructor Class in Java
Next article icon

java.lang.reflect.Field Class in Java

Last Updated : 09 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather than at compile time .Java, like many other languages, is statically typed. Reflection mechanisms allow one to bypass it to some degree, and introduce some more dynamic features, like, say, retrieval of the value of the field by name. The package java.lang.reflect includes several interfaces. Of special interest is Member which defines methods that allow getting information about a field, constructor or method of a class. There are also ten classes in this package i.e. AccessibleObject, Array, Constructor, Executable, Field, Method, Modifier, Parameter, Proxy, ReflectPermission.

The following application illustrates a simple use of java reflection. It prints the fields of the class java.awt.Dimension. The program begins with forName() method of Class to get a class object for java.awt.Dimension. Once this is obtained, getFields() is used to analyze the class object. They return an array of Field objects that provide information about the object.

Method                     Description                                                                                
equals (Object obj )This method compares this field against the specified object.
getAnnotatedType ()This method returns an AnnotatedType object that represents the use of a type to specify the declared type of the field represented by this Field
getAnnotation()This method returns this element's annotation for the specified type if such an annotation is present, else null.
getAnnotationByType()This method returns annotations that are associated with this element
getBoolean(Object obj )This method gets the value of a static or instance boolean field
getByte(Object obj )This method gets the value of a static or instance byte field
getChar(Object obj )This method gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion
getDeclaredAnnotations()This method returns annotations that are directly present on this element
getDeclaringClass()This method returns the Class object representing the class or interface that declares the field represented by this Field object
getDouble(Object obj )This method gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion
getFloat(Object obj )This method gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion
getGenericType()This method returns a Type object that represents the declared type for the field represented by this Field object
getInt(Object obj )This method returns a Type object that represents the declared type for the field represented by this Field object
getLong(Object obj )This method gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion
getModifiers()This method returns the Java language modifiers for the field represented by this Field object, as an integer
getName()This method returns the name of the field represented by this Field object
getShort(Object obj )This method gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion
hashCode()This method returns a hashcode for this Field.
isEnumConstant()This method returns true if this field represents an element of an enumerated type; returns false otherwise
isSynthetic()This method returns true if this field is a synthetic field; returns false otherwise
setBoolean(Object obj , boolean z)This method sets the value of a field as a boolean on the specified object
setByte(Object obj, byte b)This method sets the value of a field as a byte on the specified object
setChar(Object obj, char c)This method sets the value of a field as a char on the specified object
setDouble(Object obj, double d)This method sets the value of a field as a double on the specified object
setFloat(Object obj, float f)This method sets the value of a field as a float on the specified object
setInt(Object obj, int i)This method sets the value of a field as an int on the specified object
setLong(Object obj, long l)This method sets the value of a field as a long on the specified object
setShort(Object obj, short s)This method sets the value of a field as a short on the specified object
toGenericString()This method returns a string describing this Field, including its generic type
toString()This method returns a string describing this Field

Example 1:

Java
import java.lang.reflect.Field;     public class GFG {         public static void main(String[] args)          throws Exception      {             // Create the User class object          User user = new User();             // Get the all field objects of User class          Field[] fields = User.class.getFields();             for (int i = 0; i < fields.length; i++) {                 // get value of the fields              Object value = fields[i].get(user);                 // print result              System.out.println("Value of Field "                                + fields[i].getName()                                 + " is " + value);          }      }  }     // sample User class  class User {         public static String name = "Dipsundar";         public static String getName()      {          return name;      }         public static void setName(String name)      {          User.name = name;      }  } 

Output
Value of Field name is Dipsundar

Example 2:

Java
import java.lang.reflect.Field;  public class GFG {      public static void main(String[] args) throws Exception     {          // Create the User class object         User user = new User();          // Get the all field objects of User class         Field[] fields = User.class.getFields();          for (int i = 0; i < fields.length; i++) {              // get value of the fields             Object value = fields[i].get(user);              // print result             System.out.println("Value of Field "                                + fields[i].getName()                                + " is " + value);         }     } }  // sample User class class User {      public static String name = "Dipsundar";      public static String getName() { return name; }      public static void setName(String name)     {         User.name = name;     } } 

Output
Value of Field booleanValue is false

Next Article
java.lang.reflect.Constructor Class in Java
author
dipsundarmondal
Improve
Article Tags :
  • Java
  • java-lang-reflect-package
Practice Tags :
  • Java

Similar Reads

  • java.lang.reflect.Proxy Class in Java
    A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements Seria
    4 min read
  • java.lang.reflect.Method Class in Java
    java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method). This class allows broadening of conversions to oc
    3 min read
  • java.lang.reflect.Modifier Class in Java
    The java.lang.reflect.Modifier class contains methods used to get information about class, member and method access modifiers. The modifiers are represented as int value with set bits at distinct positions. The int value represents different modifiers. These values are taken from the tables in secti
    7 min read
  • java.lang.reflect.Constructor Class in Java
    java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will hav
    4 min read
  • java.lang.reflect.Parameter Class in Java
    java.lang.reflect.Parameter class provides Information about method parameters, including their name and modifiers. It also provides an alternate means of obtaining attributes for the parameter. Some useful methods of Parameter class are: public int getModifiers(): It returns the modifier flags for
    4 min read
  • Java.lang.Class class in Java | Set 1
    Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It
    15+ min read
  • Java.lang.Class class in Java | Set 2
    Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and in
    15+ min read
  • Java.lang.Number Class in Java
    Most of the time, while working with numbers in java, we use primitive data types. But, Java also provides various numeric wrapper sub classes under the abstract class Number present in java.lang package. There are mainly six sub-classes under Number class.These sub-classes define some useful method
    9 min read
  • Java.lang.Package Class in Java
    In Java, the package class was introduced in JDK 1.2 to encapsulate version data associated with a package. As the number of packages increases, knowing the version of the package has become important. This versioning information is retrieved and made available by the ClassLoader instance that loade
    9 min read
  • java.lang.MethodType Class in Java
    MethodType is a Class that belongs to java.lang package. This class consists of various types of methods that help in most of cases to find the method type based on the input object, or parameters of the method. All the instances of methodType are immutable. This means the objects of the methodType
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences