Field getInt() method in Java with Examples
Last Updated :
26 Aug, 2019
The getInt() method of java.lang.reflect.Field used to get the value of int which has to be static or instance field type. This method also used to get the value of another primitive type convertible to type int via a widening conversion. When a class contains a static or instance int field and we want to get the value of that field then we can use this method to return the value of Field.
Syntax:
public int getInt(Object obj)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts a single parameter obj which is the object to extract the int value from.
Return value: This method returns the value of field converted to type int.
Exception: This method throws following Exception:
- IllegalAccessException: if Field object is enforcing Java language access control and the underlying field is inaccessible.
- IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type int by a widening conversion.
- NullPointerException: if the specified object is null and the field is an instance field.
- ExceptionInInitializerError: if the initialization provoked by this method fails.
Below programs illustrate getInt() method:
Program 1:
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
Employee Employee = new Employee();
Field field
= Employee. class .getField( "Salary" );
int value = field.getInt(Employee);
System.out.println( "Value of int Field"
+ " Salary is " + value);
}
}
class Employee {
public static int Salary = 34113 ;
public static String name = "Aman" ;
public static int getSalary()
{
return Salary;
}
public static void setSalary( int Salary)
{
Employee.Salary = Salary;
}
public static String getName()
{
return name;
}
public static void setName(String name)
{
Employee.name = name;
}
}
|
Output:
Value of int Field Salary is 34113
Program 2:
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
IntNumbers Int = new IntNumbers();
Field field
= IntNumbers. class .getField( "value" );
int value = field.getInt(Int);
System.out.println( "Value: " + value);
}
static class IntNumbers {
public static int value = 999994567 ;
public static int getValue()
{
return value;
}
public static void setValue( int value)
{
IntNumbers.value = value;
}
}
}
|
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getInt-java.lang.Object-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...