Java Field getByte()方法及示例
java.lang.reflect .Field 的 getByte() 方法用于获取静态或实例字段类型的字节的值。当一个类包含一个静态或实例字节字段,并且我们想获得该字段的值时,我们可以使用这个方法来返回字段的值。
语法
public Byte getByte(Object obj) throws IllegalArgumentException, IllegalAccessException
参数: 该方法接受一个单参数 obj ,它是要提取字节值的对象。
返回值: 该方法返回转换为字节类型的字段的值。
异常: 该方法抛出以下异常。
- IllegalAccessException: 如果Field对象正在执行Java语言的访问控制,而底层字段是不可访问的,就会抛出这个异常。IllegalArgumentException: 如果指定的对象不是声明底层字段的类或接口的实例,或者如果字段值不能通过拓扑转换而转换为字节类型,则抛出该异常。NullPointerException: 如果指定的对象是空的,并且该字段是一个实例字段,就会抛出这个异常。ExceptionInitializerError: 如果该方法引发的初始化失败,则抛出该异常。
以下程序说明了getByte()方法:
程序1 :
// Java program to demonstrate the getByte() 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 identificationByte field object Field field = User.class .getField("identificationByte"); // Apply getByte Method on User Object // to get the value of identificationByte field byte value = field.getByte(user); // print result System.out.println("Value of Byte Field" + " identificationByte is " + value); // Now Get the selectionByte field object field = User.class.getField("selectionByte"); // Apply getByte Method on User Object // to get the value of selectionByte field value = field.getByte(user); // print result System.out.println("Value of Byte Field" + " selectionByte is " + value); }} // sample User classclass User { // static Byte values public static byte identificationByte = 'E'; public static byte selectionByte = 121; // getter and setter methods public static byte getIdentificationByte() { return identificationByte; } public static void setIdentificationByte(byte identificationByte) { User.identificationByte = identificationByte; } public static byte getSelectionByte() { return selectionByte; } public static void setSelectionByte(byte selectionByte) { User.selectionByte = selectionByte; }}
输出:
Value of Byte Field identificationByte is 69Value of Byte Field selectionByte is 121
程序2
// Java program to demonstrate the getByte() method import java.lang.reflect.Field; import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { // Create the Codes class object Codes codes = new Codes(); // Get the value field object Field field = Codes.class.getField("value"); // Apply getByte Method on field Object // to get the value of value field byte value = field.getByte(codes); // print result System.out.println("Value: " + value); }}// Codes classclass Codes { // Byte field public static byte value = 12;}输出:
Value: 12
参考文献 : https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getByte-java.lang.Object-
