Skip to content
Related Articles

Related Articles

java.lang.reflect.Field Class in Java
  • Last Updated : 09 Mar, 2021

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :