Field setByte() method in Java with Examples
Last Updated :
17 Jan, 2023
setByte() method of java.lang.reflect.Field used to set the value of a field as a byte on the specified object. When you need to set the value of a field of an object as byte then you can use this method to set value over an Object. Syntax:
public void setByte(Object obj, byte b)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts two parameters:
- obj: which is the object whose field should be modified and
- b: 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 setByte() 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 leaveLeft before "
+ "applying setByte is "
+ emp.leaveLeft);
Field field
= Employee. class
.getField("leaveLeft");
field.setByte(emp, ( byte ) 2 );
System.out.println(
"Value of leaveLeft after "
+ "applying setByte is "
+ emp.leaveLeft);
System.out.println(
"Value of age before "
+ "applying setByte is "
+ emp.age);
field = Employee. class .getField("age");
field.setByte(emp, ( byte ) 56 );
System.out.println(
"Value of age after "
+ "applying setByte is "
+ emp.age);
}
}
class Employee {
public static byte age = 45 ;
public static byte leaveLeft = 12 ;
}
|
Output:
Value of leaveLeft before applying setByte is 12
Value of leaveLeft after applying setByte is 2
Value of age before applying setByte is 45
Value of age after applying setByte is 56
Program 2:
Java
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
User user = new User();
Field field = User. class
.getField("id");
field.setByte(user, ( byte ) 20 );
System.out.println(
"Value after "
+ "applying setByte is "
+ user.id);
}
}
class User {
public static byte id = 2 ;
}
|
Output:
Value after applying setByte is 20
Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setByte-java.lang.Object-byte-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...