java.lang.reflect.Field的getInt()方法用于获取必须为静态或实例字段类型的int值。此方法还用于获取通过扩展转换可转换为int类型的另一个基本类型的值。当一个类包含一个静态或实例int字段并且我们想要获取该字段的值时,则可以使用此方法返回Field的值。
用法:
public int getInt(Object obj)
throws IllegalArgumentException,
IllegalAccessException
参数:此方法接受单个参数obj,它是要从中提取int值的对象。
返回值:此方法返回转换为int类型的字段的值。
异常:此方法引发以下异常:
IllegalAccessException:如果Field对象正在强制执行Java语言访问控制,并且基础字段不可访问。
IllegalArgumentException:如果指定的对象不是声明基础字段的类或接口的实例,或者无法通过扩展转换将字段值转换为int类型,则为false。
NullPointerException :如果指定的对象为null并且该字段是实例字段。
ExceptionInInitializerError:如果此方法引发的初始化失败。
以下示例程序旨在说明getInt()方法:
示例1:
// Java program to demonstrate getInt() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// Create the Employee class object
Employee Employee = new Employee();
// Get the Salary field object
Field field
= Employee.class.getField("Salary");
// Apply getInt Method on Employee Object
// to get the value of Salary field
int value = field.getInt(Employee);
// print result
System.out.println("Value of int Field"
+ " Salary is " + value);
}
}
// sample Employee class
class Employee {
// static int values
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;
}
}
输出:
Value of int Field Salary is 34113
示例2:
// Java program to demonstrate getInt() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// Create the IntNumbers class object
IntNumbers Int = new IntNumbers();
// Get the value field object
Field field
= IntNumbers.class.getField("value");
// Apply getInt Method on field Object
// to get the value of value field
int value = field.getInt(Int);
// print result
System.out.println("Value: " + value);
}
// IntNumbers class
static class IntNumbers {
// int field
public static int value = 999994567;
// getter and setter methods
public static int getValue()
{
return value;
}
public static void setValue(int value)
{
IntNumbers.value = value;
}
}
}
输出:
Value: 999994567