Java中的Array getByte()方法

Java中的Array getByte()方法

java.lang.reflect.Array.getByte() 是Java中的内置方法,用于将指定数组中给定索引处的元素作为Byte返回。

语法:

Array.getByte(Object[] array, int index)

参数: 该方法接受两个强制参数:

  • array: 要返回其索引的对象数组。
  • index: 给定数组中的特定索引。返回给定数组中“索引”处的元素。

返回值: 该方法返回数组的元素为byte。

异常: 该方法会抛出以下异常:

  • NullPointerException - 当数组为空时。
  • IllegalArgumentException - 当给定的对象数组不是一个Array。
  • ArrayIndexOutOfBoundsException - 如果给定的索引不在数组大小的范围内。

下面的程序说明了Array的get()方法:

程序1:

import java.lang.reflect.Array;
 
public class GfG {
    // main method
    public static void main(String[] args)
    {
        // 声明并定义一个byte数组
        byte a[] = { 1, 2, 3, 4, 5 };
 
        // 遍历数组
        for (int i = 0; i < 5; i++) {
 
            // Array.getByte 方法
            byte x = Array.getByte(a, i);
 
            // 打印值
            System.out.print(x + " ");
        }
    }
}

输出:

1 2 3 4 5

程序2: 演示ArrayIndexOutOfBoundsException。

import java.lang.reflect.Array;
 
public class GfG {
    // main method
    public static void main(String[] args)
    {
        // 声明并定义一个int数组
        int a[] = { 1, 2, 3, 4, 5 };
 
        try {
            // 无效的索引
            // Array.getByte 方法
            byte x = Array.getByte(a, 6);
 
            System.out.println(x);
        }
        catch (Exception e) {
            // 抛出异常
            System.out.println("Exception : " + e);
        }
    }
}

输出:

Exception : java.lang.ArrayIndexOutOfBoundsException

程序3: 演示NullPointerException。

import java.lang.reflect.Array;
 
public class GfG {
    // main method
    public static void main(String[] args)
    {
        // 声明一个int数组
        int a[];
 
        // 将数组设置为null
        a = null;
 
        try {
            // null Object 数组
            // Array.getByte 方法
            byte x = Array.getByte(a, 6);
 
            System.out.println(x);
        }
        catch (Exception e) {
            // 抛出异常
            System.out.println("Exception : " + e);
        }
    }
}

输出:

Exception : java.lang.NullPointerException

程序4: 演示IllegalArgumentException。

import java.lang.reflect.Array;
 
public class GfG {
    // 主方法
    public static void main(String[] args)
    {
        // 整数(非数组)
        int y = 0;
 
        try {
            // 非法参数
            // Array.getByte 方法
            byte x = Array.getByte(y, 6);
 
            System.out.println(x);
        }
        catch (Exception e) {
            // 抛出异常
            System.out.println("异常:" + e);
        }
    }
}

输出:

异常:java.lang.IllegalArgumentException:参数不是数组

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程