java.lang.reflect.Field的getFloat()方法用于获取必须为静态或实例字段类型的float值。此方法还用于获取通过扩展转换可转换为float类型的另一个原始类型的值。当类包含静态或实例浮点型字段并且我们想要获取该字段的值时,可以使用此方法返回Field的值。
用法:
public float getFloat(Object obj)
throws IllegalArgumentException,
IllegalAccessException
参数:此方法接受单个参数obj,它是要从中提取浮点值的对象。
返回值:此方法返回转换为float类型的字段的值。
异常:此方法引发以下异常:
IllegalAccessException:如果Field对象正在强制执行Java语言访问控制并且基础字段不可访问,则抛出此异常。
IllegalArgumentException:如果指定的对象不是声明基础字段的类或接口的实例,或者如果不能通过扩展转换将字段值转换为float类型,则抛出此异常。
NullPointerException :如果指定对象为null并且该字段是实例字段,则抛出此异常。
ExceptionInInitializerError:如果此方法引发的初始化失败,则抛出此异常。
以下示例程序旨在说明getFloat()方法:
示例1:
// Java program to demonstrate the getFloat() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws NoSuchFieldException,
SecurityException,
IllegalArgumentException,
IllegalAccessException
{
// Create the User class object
User user = new User();
// Get the marks field object
Field field = User.class.getField("Marks");
// Apply getFloat Method on User Object
// to get the value of Marks field
float value = field.getFloat(user);
// print result
System.out.println("Value of float Field"
+ " Marks is " + value);
// Now Get the Fees field object
field = User.class.getField("Fees");
// Apply getFloat Method on User Object
// to get the value of Fees field
value = field.getFloat(user);
// print result
System.out.println("Value of float Field"
+ " Fees is " + value);
}
}
// sample User class
class User {
// static float values
public static float Marks = 94.13f;
public static float Fees = 1343413.99f;
public static String name = "Aman";
public static float getMarks()
{
return Marks;
}
public static void setMarks(float marks)
{
Marks = marks;
}
public static float getFees()
{
return Fees;
}
public static void setFees(float fees)
{
Fees = fees;
}
public static String getName()
{
return name;
}
public static void setName(String name)
{
User.name = name;
}
}
输出:
Value of float Field Marks is 94.13
Value of float Field Fees is 1343414.0
示例2:
// Java program to demonstrate the getFloat() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws NoSuchFieldException,
SecurityException,
IllegalArgumentException,
IllegalAccessException
{
// Create the RealNumbers class object
RealNumbers real = new RealNumbers();
// Get the value field object
Field field
= RealNumbers.class
.getField("value");
// Apply getFloat Method on field Object
// to get the value of value field
float value = field.getFloat(real);
// print result
System.out.println("Value: " + value);
}
// RealNumbers class
static class RealNumbers {
// float field
public static float value
= 123432123.1234f;
// getter and setter methods
public static float getValue()
{
return value;
}
public static void setValue(float value)
{
RealNumbers.value = value;
}
}
}
输出:
Value: 1.2343212E8