Java源码学习-java.lang.Byte

431 阅读4分钟

呀!周末是过的真快呀!莫慌,这不周一又过完了吗?过完这周,不就马上回家过年了吗!我们接着奏乐接着舞...

书接上文,我们大致学习了一下Object类相关的源码,现在我们来看一下Byte类。
Byte 类将原始类型 byte 的值包装在一个对象中。 Byte 类型的对象包含一个类型为 byte 的字段。 此外,该类提供了几种将字节转换为字符串和将字符串转换为字节的方法,以及在处理字节时有用的其他常量和方法。

首先我们看一下类名及其结构:

public final class Byte extends Number implements Comparable<Byte> 

image.png
由此可知,Byte类继承了 Number 类并实现了 Comparable 接口,但被final修饰,不可被其它类继承。

一、类中常量及变量

类中静态成员变量有5个,分别为:

//用于java的序列化机制
private static final long serialVersionUID = -7183698231559129828L;
//用于以二进制补码形式表示一个byte的位数。(也就是说表示一个byte需用8位二进制补码表示)
public static final int SIZE = 8;
//用于以二进制补码形式表示一个byte的字节数。(也就是说表示一个byte需一个字节数)
public static final int BYTES = SIZE / Byte.SIZE;
//表示一个byte类型的变量的值的范围为 $-2^7$ ~ $2^7-1$
public static final byte   MIN_VALUE = -128;
public static final byte   MAX_VALUE = 127;

成员变量有一个,用于存储被包装的byte的值。且被final修饰,在Byte类中在构造器中赋值。

private final byte value;

二、类构造方法

@Deprecated(since="9")
public Byte(byte value) {
    this.value = value;
}

public Byte(String s) throws NumberFormatException {
    this.value = parseByte(s, 10);
}

仅有有参构造器,也就是说我们new Byte时必须指定被包装的byte值,否则会报错。

image.png

第二个构造器传入字符串s,我们传入一个字符串"128"来debug一下,如图所示,首先会调用parseByte("128", 10)。 image.png
我们进入本类中的parseByte方法,发现调用的是Integer.parseInt(s, radix)方法。 image.png 我们进入Integer类中parseInt方法:

public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */
        //若s为null,则抛出异常
        if (s == null) {
            throw new NumberFormatException("null");
        }
        //若进制radix小于Character.MIN_RADIX(为2),抛出异常
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        //若进制radix大于Character.MAX_RADIX(为36),抛出异常
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;
        //若字符串s的首字符<'0',则判断是否为正负号,若长度仅为1,则抛出异常。
        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            //将字符串s的每一位(从高位到低位)依次转换为radix进制中的一位。
            //如“128”,第一次循环结束result = -1,第二次循环结束,result = -12
            //第三次循环结束,result = -128,最后返回 -result = 128(十进制)
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                //Character.digit(c, radix)该方法返回指定字符 c 的 radix 进制的数值。
                //如果进制不在 MIN_RADIX ≤ radix ≤ MAX_RADIX 范围内,
                //或者如果 c 的值不是指定进制中的有效数字,则返回 -1。
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

最后parseByte("128", 10)将字符串类型s -> 10进制的i,然后强转为byte(并保证128i127-128\leq i\leq127)复制给Byte对象中的value以完成对象的构造。

三、类中相关方法

    //返回表示此 Byte 值的 String 对象。 该值被转换为带符号的十进制表示并以字符串形式返回,
    //就像将字节值作为参数提供给 toString(byte) 方法一样。
    public static String toString(byte b) {
        return Integer.toString((int)b, 10);
    }
    //ByteCache是Byte的一个内部类,它包含了Byte可能值的Byte数组,[-128,127],并将这个范围内的值缓存起来。
    private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }
    //将byte转换为包装类型Byte
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    //将字符串s解析成带符号的十进制byte
    public static byte parseByte(String s) throws NumberFormatException {
        return parseByte(s, 10);
    }
    //返回一个Byte对象,该对象保存字符串s解析成radix进制后的值。
    public static Byte valueOf(String s, int radix)
        throws NumberFormatException {
        return valueOf(parseByte(s, radix));
    }
    //实际掉用的是上一方法,指定进制为10进制。
    public static Byte valueOf(String s) throws NumberFormatException {
        return valueOf(s, 10);
    }
    //将字符串 nm 解析为 Byte
    public static Byte decode(String nm) throws NumberFormatException {
        int i = Integer.decode(nm);
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                    "Value " + i + " out of range from input " + nm);
        return valueOf((byte)i);
    }
    //返回Byte对象中被包装的byte值
    public byte byteValue() {
        return value;
    }
    //返回Byte对象中被包装的byte的值并强转为short
    public short shortValue() {
        return (short)value;
    }
    //返回Byte对象中被包装的byte的值并强转为int
    public int intValue() {
        return (int)value;
    }
    //返回Byte对象中被包装的byte的值并强转为long
    public long longValue() {
        return (long)value;
    }
    //返回Byte对象中被包装的byte的值并强转为float
    public float floatValue() {
        return (float)value;
    }
    //返回Byte对象中被包装的byte的值并强转为double
    public double doubleValue() {
        return (double)value;
    }

    public String toString() {
        return Integer.toString((int)value);
    }
    //返回这个Byte对象的哈希值
    @Override
    public int hashCode() {
        return Byte.hashCode(value);
    }

    public static int hashCode(byte value) {
        return (int)value;
    }
    //将此对象与指定对象比较,并返回比较后结果。
    public boolean equals(Object obj) {
        if (obj instanceof Byte) {
            return value == ((Byte)obj).byteValue();
        }
        return false;
    }

    public int compareTo(Byte anotherByte) {
        return compare(this.value, anotherByte.value);
    }
    //通过相减来比较,大于0则说明x大于y。
    public static int compare(byte x, byte y) {
        return x - y;
    }
    //将byte x转化为无符号整型,先将x强转为int,再和 0xff 按位与。
    public static int toUnsignedInt(byte x) {
        return ((int) x) & 0xff;
    }
    //将byte x转化为无符号long型,先将x强转为long,再和 0xffL 按位与。
    public static long toUnsignedLong(byte x) {
        return ((long) x) & 0xffL;
    }

该博客仅为初学者自我学习的记录,粗浅之言,如有不对之处,恳请指正。