Field setFloat() method in Java with Examples
Last Updated :
13 Jan, 2023
setFloat() method of java.lang.reflect.Field used to set the value of a field as a float on the specified object. When you need to set the value of a field of an object as a float then you can use this method to set value over an Object. Syntax:
public void setFloat(Object obj, float f)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts two parameters:
- obj: which is the object whose field should be modified and
- f: which is the new value for the field of obj being modified.
Return: This method returns nothing. Exception: This method throws the following Exception:
- IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final.
- IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementer thereof), or if an unwrapping conversion fails.
- 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 setFloat() method: Program 1:
Java
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
Employee emp = new Employee();
System.out.println(
"Value of salary before "
+ "applying setFloat is "
+ emp.salary);
Field field = Employee. class .getField("salary");
field.setFloat(emp, 259939 .99f);
System.out.println(
"Value of salary after "
+ "applying setFloat is "
+ emp.salary);
System.out.println(
"Value of pf before "
+ "applying setFloat is "
+ emp.pf);
field = Employee. class .getField("pf");
field.setFloat(emp, 234234 .34f);
System.out.println(
"Value of pf after "
+ "applying setFloat is "
+ emp.pf);
}
}
class Employee {
public static float pf = 122342 .89f;
public static float salary = 143125f;
}
|
Output:
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
Program 2:
Java
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
Numbers no = new Numbers();
Field field = Numbers. class
.getField("value");
field.setFloat(no, 3244 .466f);
System.out.println(
"Value after "
+ "applying setFloat is "
+ Numbers.value);
}
}
class Numbers {
public static float value = 26774 .3685f;
}
|
Output:
Value after applying setFloat is 3244.466
Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setFloat-java.lang.Object-float-
Share your thoughts in the comments
Please Login to comment...