Field setDouble() method in Java with Examples
Last Updated :
10 Jan, 2023
setDouble() method of java.lang.reflect.Field used to set the value of a field as a double on the specified object. When you need to set the value of a field of an object as double then you can use this method to set value over an Object.
Syntax:
public void setDouble(Object obj, double d)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts two parameters:
- obj: which is the object whose field should be modified and
- d: 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 setDouble() 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 setDouble is "
+ emp.salary);
Field field = Employee. class
.getField("salary");
field.setDouble(emp, 50000.99 );
System.out.println(
"Value of salary after "
+ "applying setDouble is "
+ emp.salary);
System.out.println(
"Value of pf before "
+ "applying setDouble is "
+ emp.pf);
field = Employee. class .getField("pf");
field.setDouble(emp, 1234.34 );
System.out.println(
"Value of pf after "
+ "applying setDouble is "
+ emp.pf);
}
}
class Employee {
public static double pf = 2342.89 ;
public static double salary = 43125 ;
}
|
Output:
Value of salary before applying setDouble is 43125.0
Value of salary after applying setDouble is 50000.99
Value of pf before applying setDouble is 2342.89
Value of pf after applying setDouble is 1234.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.setDouble(no, 53245.466 );
System.out.println(
"Value after "
+ "applying setDouble is "
+ Numbers.value);
}
}
class Numbers {
public static double value = 1232.3685 ;
}
|
Output:
Value after applying setDouble is 53245.466
Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setDouble-java.lang.Object-double-
Share your thoughts in the comments
Please Login to comment...