java.lang.reflect.Field的setFloat()方法用於將字段的值設置為指定對象上的float。當需要將對象的字段值設置為浮點型時,可以使用此方法在對象上設置值。
用法:
public void setFloat(Object obj, float f) throws IllegalArgumentException, IllegalAccessException
參數:此方法接受接受兩個參數:
- obj:是應該修改其字段的對象,並且
- f:這是要修改的obj字段的新值。
返回:此方法不返回任何內容。
異常:此方法引發以下異常:
- IllegalAccessException:如果此Field對象正在強製執行Java語言訪問控製,並且基礎字段是不可訪問的或最終的。
- IllegalArgumentException:如果指定的對象不是聲明基礎字段(或其子類或實現者)的類或接口的實例,或者展開轉換失敗。
- NullPointerException:如果指定的對象為null,並且該字段是實例字段。
- ExceptionInInitializerError:如果此方法引發的初始化失敗。
以下示例程序旨在說明setFloat()方法:
示例1:
// Java program to illustrate setFloat() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// create user object
Employee emp = new Employee();
// print value of salary
System.out.println(
"Value of salary before "
+ "applying setFloat is "
+ emp.salary);
// Get the marks field object
Field field = Employee.class.getField("salary");
// Apply setFloat Method
field.setFloat(emp, 259939.99f);
// print value of salary
System.out.println(
"Value of salary after "
+ "applying setFloat is "
+ emp.salary);
// print value of pf
System.out.println(
"Value of pf before "
+ "applying setFloat is "
+ emp.pf);
// Get the marks field object
field = Employee.class.getField("pf");
// Apply setFloat Method
field.setFloat(emp, 234234.34f);
// print value of pf
System.out.println(
"Value of pf after "
+ "applying setFloat is "
+ emp.pf);
}
}
// sample class
class Employee {
// static float values
public static float pf = 122342.89f;
public static float salary = 143125f;
}
輸出:
Value of salary before applying setFloat is 143125.0 Value of salary after applying setFloat is 259939.98 Value of pf before applying setFloat is 122342.89 Value of pf after applying setFloat is 234234.34
示例2:
// Java program to illustrate setFloat() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// create Numbers object
Numbers no = new Numbers();
// Get the value field object
Field field = Numbers.class
.getField("value");
// Apply setFloat Method
field.setFloat(no, 3244.466f);
// print value of isActive
System.out.println(
"Value after "
+ "applying setFloat is "
+ Numbers.value);
}
}
// sample Numbers class
class Numbers {
// static float value
public static float value = 26774.3685f;
}
輸出:
Value after applying setFloat is 3244.466
相關用法
- Java Array setFloat()用法及代碼示例
- Java Field set()用法及代碼示例
- Java Field get()用法及代碼示例
- Java Field setLong()用法及代碼示例
- Java Field setChar()用法及代碼示例
- Java Field getModifiers()用法及代碼示例
- Java Field setByte()用法及代碼示例
- Java Field isEnumConstant()用法及代碼示例
- Java Field getGenericType()用法及代碼示例
- Java Field setInt()用法及代碼示例
- Java Field setDouble()用法及代碼示例
- Java Field getDouble()用法及代碼示例
- Java Field getFloat()用法及代碼示例
- Java Field getChar()用法及代碼示例
- Java Field getDeclaringClass()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Field setFloat() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。