深入学习java源码之 Array.newInstance()与Array.getLong()

深入学习java源码之 Array.newInstance()与Array.getLong()

Array类提供静态方法来动态创建和访问Java数组。 
Array允许在获取或设置操作期间扩大转换,但如果发生缩小转换,则抛出IllegalArgumentException 。 

创建具有指定组件类型和长度的新数组。 调用此方法相当于创建一个数组,如下所示: 

 int[] x = {length};
 Array.newInstance(componentType, x);

方法

Modifier and Type Method and Description
static Object get(Object array, int index)

返回指定数组对象中的索引组件的值。

static boolean getBoolean(Object array, int index)

返回指定数组对象中的索引组件的值,如 boolean

static byte getByte(Object array, int index)

返回指定数组对象中的索引组件的值,如 byte

static char getChar(Object array, int index)

返回指定数组对象中索引组件的值,如 char

static double getDouble(Object array, int index)

返回指定数组对象中的索引组件的值,如 double

static float getFloat(Object array, int index)

返回指定数组对象中的索引组件的值,如 float

static int getInt(Object array, int index)

返回指定数组对象中的索引组件的值,如 int

static int getLength(Object array)

返回指定数组对象的长度,如 int

static long getLong(Object array, int index)

返回指定数组对象中索引组件的值,如 long

static short getShort(Object array, int index)

返回指定数组对象中的索引组件的值,如 short

static Object newInstance(<?> componentType, int... dimensions)

创建具有指定组件类型和尺寸的新数组。

static Object newInstance(<?> componentType, int length)

创建具有指定组件类型和长度的新数组。

static void set(Object array, int index, Object value)

将指定数组对象的索引组件的值设置为指定的新值。

static void setBoolean(Object array, int index, boolean z)

将指定数组对象的索引组件的值设置为指定的 boolean值。

static void setByte(Object array, int index, byte b)

将指定数组对象的索引组件的值设置为指定的 byte值。

static void setChar(Object array, int index, char c)

将指定数组对象的索引组件的值设置为指定的 char值。

static void setDouble(Object array, int index, double d)

将指定数组对象的索引组件的值设置为指定的 double值。

static void setFloat(Object array, int index, float f)

将指定数组对象的索引组件的值设置为指定的 float值。

static void setInt(Object array, int index, int i)

将指定数组对象的索引组件的值设置为指定的 int值。

static void setLong(Object array, int index, long l)

将指定数组对象的索引组件的值设置为指定的 long值。

static void setShort(Object array, int index, short s)

将指定数组对象的索引组件的值设置为指定的 short值。

java源码

package java.lang.reflect;

public final
class Array {

    private Array() {}

    public static Object newInstance(Class<?> componentType, int length)
        throws NegativeArraySizeException {
        return newArray(componentType, length);
    }

    public static Object newInstance(Class<?> componentType, int... dimensions)
        throws IllegalArgumentException, NegativeArraySizeException {
        return multiNewArray(componentType, dimensions);
    }

    public static native int getLength(Object array)
        throws IllegalArgumentException;


    public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native boolean getBoolean(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native byte getByte(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;


    public static native char getChar(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native short getShort(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native int getInt(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native long getLong(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native float getFloat(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native double getDouble(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setBoolean(Object array, int index, boolean z)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setByte(Object array, int index, byte b)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setChar(Object array, int index, char c)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setShort(Object array, int index, short s)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setInt(Object array, int index, int i)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setLong(Object array, int index, long l)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setFloat(Object array, int index, float f)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

    public static native void setDouble(Object array, int index, double d)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;


    private static native Object newArray(Class<?> componentType, int length)
        throws NegativeArraySizeException;

    private static native Object multiNewArray(Class<?> componentType,
        int[] dimensions)
        throws IllegalArgumentException, NegativeArraySizeException;


}

抛出一个应用程序尝试创建一个负数大小的数组。

package java.lang;

public
class NegativeArraySizeException extends RuntimeException {
    private static final long serialVersionUID = -8960118058596991861L;

    public NegativeArraySizeException() {
        super();
    }

    public NegativeArraySizeException(String s) {
        super(s);
    }
}

抛出表示一种方法已经通过了非法或不正确的参数。 

package java.lang;

public
class IllegalArgumentException extends RuntimeException {

    public IllegalArgumentException() {
        super();
    }

    public IllegalArgumentException(String s) {
        super(s);
    }

    public IllegalArgumentException(String message, Throwable cause) {
        super(message, cause);
    }

    public IllegalArgumentException(Throwable cause) {
        super(cause);
    }

    private static final long serialVersionUID = -5365630128856068164L;
}

抛出以表示使用非法索引访问数组。 索引为负数或大于或等于数组的大小。 

package java.lang;

public
class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException {
    private static final long serialVersionUID = -5116101128118950844L;

    public ArrayIndexOutOfBoundsException() {
        super();
    }

    public ArrayIndexOutOfBoundsException(int index) {
        super("Array index out of range: " + index);
    }

    public ArrayIndexOutOfBoundsException(String s) {
        super(s);
    }
}

抛出以表示某种索引(例如数组,字符串或向量)的索引超出范围。 
应用程序可以将此类子类化以指示类似的异常。 

package java.lang;

public
class IndexOutOfBoundsException extends RuntimeException {
    private static final long serialVersionUID = 234122996006267687L;

    public IndexOutOfBoundsException() {
        super();
    }

    public IndexOutOfBoundsException(String s) {
        super(s);
    }
}

RuntimeException是在Java虚拟机的正常操作期间可以抛出的那些异常的超类。 
RuntimeException及其子类是未经检查的异常 。 unchecked异常不需要在方法或构造函数的拟申报throws条款,如果他们可以通过该方法或构造函数的执行被抛出和方法或构造边界之外传播。 

package java.lang;

public class RuntimeException extends Exception {
    static final long serialVersionUID = -7034897190745766939L;

    public RuntimeException() {
        super();
    }

    public RuntimeException(String message) {
        super(message);
    }

    public RuntimeException(String message, Throwable cause) {
        super(message, cause);
    }

    public RuntimeException(Throwable cause) {
        super(cause);
    }

    protected RuntimeException(String message, Throwable cause,
                               boolean enableSuppression,
                               boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

类异常及其子类是形式Throwable指示合理的应用程序想要捕获的条件。 
异常类和任何不是RuntimeException的子类的子类都是检查异常 。 检查的异常需要在方法或构造函数的throws子句中声明,如果它们可以通过执行方法或构造函数抛出,并在方法或构造函数边界之外传播。 

package java.lang;

public class Exception extends Throwable {
    static final long serialVersionUID = -3387516993124229948L;

    public Exception() {
        super();
    }

    public Exception(String message) {
        super(message);
    }

    public Exception(String message, Throwable cause) {
        super(message, cause);
    }

    public Exception(Throwable cause) {
        super(cause);
    }

    protected Exception(String message, Throwable cause,
                        boolean enableSuppression,
                        boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

Throwable类是Java语言中所有错误和异常的Throwable类。 只有作为此类(或其一个子类)的实例的对象由Java虚拟机抛出,或者可以由Java throw语句抛出。 类似地,只有这个类或其子类可以是catch子句中的参数类型。 对于异常,编译时检查的目的Throwable和任何子类Throwable ,是不是也无论是子类RuntimeException或Error被视为检查的异常。 
通常使用两个子类的实例Error和异常来表示出现异常情况。 通常,这些实例是在特殊情况的上下文中新创建的,以便包括相关信息(如堆栈跟踪数据)。 

throwable在创建时包含其线程的执行堆栈的快照。 它还可以包含一个消息字符串,其中提供有关错误的更多信息。 随着时间的推移,一个可以抛出的其他可抛物线可以被传播。 最后,throwable也可能包含一个原因 :另一个可抛出的,导致这个可抛出的构造。 这种因果信息的记录被称为链接的异常设施,因为原因本身可能有原因等等,导致“链”的异常,每个异常都由另一个导致。 

抛出一个原因的一个原因是抛出它的类被构建在较低层次的抽象之上,上层的操作由于下层的故障而失败。 让下层投掷的投掷物向外传播是不好的设计,因为它通常与上层提供的抽象无关。 此外,这样做会将上层的API与其实现的细节相结合,假设较低层的异常是被检查的异常。 抛出“包装异常”(即,包含原因的异常)允许上层将故障的细节传达给其呼叫者,而不会导致这些缺点之一。 它保留了更改上层实现的灵活性,而不改变其API(特别是其方法抛出的一组异常)。 

throwable可能有一个原因的第二个原因是抛出它的方法必须符合通用接口,该接口不允许该方法直接引用原因。 例如,假设持久集合符合Collection接口,并且其持久性在java.io顶部java.io 。 假设add方法的内部可以抛出一个IOException 。 实施可以在细节沟通IOException同时符合它的调用者Collection通过封装接口IOException在适当的未经检查的异常。 (持久集合的规范应该表明它能够抛出这种异常。) 

一个原因可以通过两种方式与一个可抛出的关联:通过构造函数将原因作为参数,或通过initCause(Throwable)方法。 希望允许原因与他们相关联的新的可抛出类可以提供构造函数,这些构造函数可以引导和委派(或间接地)到Throwable函数之一的Throwable中。 因为initCause方法是公开的,它允许一个原因与任何可抛出的,即使是“传统的可抛出”相关联,其实现早于将异常链接机制添加到Throwable 。 

按照惯例,类Throwable及其子类有两个构造函数,一个不String参数,另一个String函数采用可用于生成详细消息的String参数。 此外,那些可能与之相关联的原因的子类应该有两个构造函数,一个是Throwable (原因),另一个是String (详细信息)和一个Throwable (原因)。

方法

Modifier and Type Method and Description
void addSuppressed(Throwable exception)

将指定的异常附加到为了传递此异常而被抑制的异常。

Throwable fillInStackTrace()

填写执行堆栈跟踪。

Throwable getCause()

如果原因不存在或未知,则返回此throwable的原因或 null

String getLocalizedMessage()

创建此可抛出的本地化描述。

String getMessage()

返回此throwable的详细消息字符串。

StackTraceElement[] getStackTrace()

提供对 printStackTrace()打印的堆栈跟踪信息的 编程访问

Throwable[] getSuppressed()

返回一个包含所有被抑制的异常的数组,通常由 try -with-resources语句来传递这个异常。

Throwable initCause(Throwable cause)

将此throwable的 原因初始化为指定值。

void printStackTrace()

将此throwable和其追溯打印到标准错误流。

void printStackTrace(PrintStream s)

将此throwable和其追溯打印到指定的打印流。

void printStackTrace(PrintWriter s)

将此throwable和其追溯打印到指定的打印作者。

void setStackTrace(StackTraceElement[] stackTrace)

设置将被返回的堆栈微量元素 getStackTrace()和由印刷 printStackTrace()和相关方法。

String toString()

返回此可抛出的简短描述。

package java.lang;
import  java.io.*;
import  java.util.*;

public class Throwable implements Serializable {
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -3042686055658047285L;

    private transient Object backtrace;

    private String detailMessage;

    private static class SentinelHolder {

        public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
            new StackTraceElement("", "", null, Integer.MIN_VALUE);

        public static final StackTraceElement[] STACK_TRACE_SENTINEL =
            new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
    }

    private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];

    private Throwable cause = this;

    private StackTraceElement[] stackTrace = UNASSIGNED_STACK;

    private static final List<Throwable> SUPPRESSED_SENTINEL =
        Collections.unmodifiableList(new ArrayList<Throwable>(0));

    private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;

    /** Message for trying to suppress a null exception. */
    private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";

    /** Message for trying to suppress oneself. */
    private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";

    /** Caption  for labeling causative exception stack traces */
    private static final String CAUSE_CAPTION = "Caused by: ";

    /** Caption for labeling suppressed exception stack traces */
    private static final String SUPPRESSED_CAPTION = "Suppressed: ";

    public Throwable() {
        fillInStackTrace();
    }

    public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    }

    public Throwable(String message, Throwable cause) {
        fillInStackTrace();
        detailMessage = message;
        this.cause = cause;
    }

    public Throwable(Throwable cause) {
        fillInStackTrace();
        detailMessage = (cause==null ? null : cause.toString());
        this.cause = cause;
    }

    protected Throwable(String message, Throwable cause,
                        boolean enableSuppression,
                        boolean writableStackTrace) {
        if (writableStackTrace) {
            fillInStackTrace();
        } else {
            stackTrace = null;
        }
        detailMessage = message;
        this.cause = cause;
        if (!enableSuppression)
            suppressedExceptions = null;
    }

    public String getMessage() {
        return detailMessage;
    }

    public String getLocalizedMessage() {
        return getMessage();
    }

    public synchronized Throwable getCause() {
        return (cause==this ? null : cause);
    }

    public synchronized Throwable initCause(Throwable cause) {
        if (this.cause != this)
            throw new IllegalStateException("Can't overwrite cause with " +
                                            Objects.toString(cause, "a null"), this);
        if (cause == this)
            throw new IllegalArgumentException("Self-causation not permitted", this);
        this.cause = cause;
        return this;
    }

    public String toString() {
        String s = getClass().getName();
        String message = getLocalizedMessage();
        return (message != null) ? (s + ": " + message) : s;
    }


    public void printStackTrace() {
        printStackTrace(System.err);
    }

    public void printStackTrace(PrintStream s) {
        printStackTrace(new WrappedPrintStream(s));
    }

    private void printStackTrace(PrintStreamOrWriter s) {
        // Guard against malicious overrides of Throwable.equals by
        // using a Set with identity equality semantics.
        Set<Throwable> dejaVu =
            Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
        dejaVu.add(this);

        synchronized (s.lock()) {
            // Print our stack trace
            s.println(this);
            StackTraceElement[] trace = getOurStackTrace();
            for (StackTraceElement traceElement : trace)
                s.println("\tat " + traceElement);

            // Print suppressed exceptions, if any
            for (Throwable se : getSuppressed())
                se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);

            // Print cause, if any
            Throwable ourCause = getCause();
            if (ourCause != null)
                ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
        }
    }

    private void printEnclosedStackTrace(PrintStreamOrWriter s,
                                         StackTraceElement[] enclosingTrace,
                                         String caption,
                                         String prefix,
                                         Set<Throwable> dejaVu) {
        assert Thread.holdsLock(s.lock());
        if (dejaVu.contains(this)) {
            s.println("\t[CIRCULAR REFERENCE:" + this + "]");
        } else {
            dejaVu.add(this);
            // Compute number of frames in common between this and enclosing trace
            StackTraceElement[] trace = getOurStackTrace();
            int m = trace.length - 1;
            int n = enclosingTrace.length - 1;
            while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
                m--; n--;
            }
            int framesInCommon = trace.length - 1 - m;

            // Print our stack trace
            s.println(prefix + caption + this);
            for (int i = 0; i <= m; i++)
                s.println(prefix + "\tat " + trace[i]);
            if (framesInCommon != 0)
                s.println(prefix + "\t... " + framesInCommon + " more");

            // Print suppressed exceptions, if any
            for (Throwable se : getSuppressed())
                se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
                                           prefix +"\t", dejaVu);

            // Print cause, if any
            Throwable ourCause = getCause();
            if (ourCause != null)
                ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
        }
    }

    public void printStackTrace(PrintWriter s) {
        printStackTrace(new WrappedPrintWriter(s));
    }

    private abstract static class PrintStreamOrWriter {
        /** Returns the object to be locked when using this StreamOrWriter */
        abstract Object lock();

        /** Prints the specified string as a line on this StreamOrWriter */
        abstract void println(Object o);
    }

    private static class WrappedPrintStream extends PrintStreamOrWriter {
        private final PrintStream printStream;

        WrappedPrintStream(PrintStream printStream) {
            this.printStream = printStream;
        }

        Object lock() {
            return printStream;
        }

        void println(Object o) {
            printStream.println(o);
        }
    }

    private static class WrappedPrintWriter extends PrintStreamOrWriter {
        private final PrintWriter printWriter;

        WrappedPrintWriter(PrintWriter printWriter) {
            this.printWriter = printWriter;
        }

        Object lock() {
            return printWriter;
        }

        void println(Object o) {
            printWriter.println(o);
        }
    }

    public synchronized Throwable fillInStackTrace() {
        if (stackTrace != null ||
            backtrace != null /* Out of protocol state */ ) {
            fillInStackTrace(0);
            stackTrace = UNASSIGNED_STACK;
        }
        return this;
    }

    private native Throwable fillInStackTrace(int dummy);

    public StackTraceElement[] getStackTrace() {
        return getOurStackTrace().clone();
    }

    private synchronized StackTraceElement[] getOurStackTrace() {
        // Initialize stack trace field with information from
        // backtrace if this is the first call to this method
        if (stackTrace == UNASSIGNED_STACK ||
            (stackTrace == null && backtrace != null) /* Out of protocol state */) {
            int depth = getStackTraceDepth();
            stackTrace = new StackTraceElement[depth];
            for (int i=0; i < depth; i++)
                stackTrace[i] = getStackTraceElement(i);
        } else if (stackTrace == null) {
            return UNASSIGNED_STACK;
        }
        return stackTrace;
    }

    public void setStackTrace(StackTraceElement[] stackTrace) {
        // Validate argument
        StackTraceElement[] defensiveCopy = stackTrace.clone();
        for (int i = 0; i < defensiveCopy.length; i++) {
            if (defensiveCopy[i] == null)
                throw new NullPointerException("stackTrace[" + i + "]");
        }

        synchronized (this) {
            if (this.stackTrace == null && // Immutable stack
                backtrace == null) // Test for out of protocol state
                return;
            this.stackTrace = defensiveCopy;
        }
    }

    native int getStackTraceDepth();

    native StackTraceElement getStackTraceElement(int index);

    private void readObject(ObjectInputStream s)
        throws IOException, ClassNotFoundException {
        s.defaultReadObject();     // read in all fields
        if (suppressedExceptions != null) {
            List<Throwable> suppressed = null;
            if (suppressedExceptions.isEmpty()) {
                // Use the sentinel for a zero-length list
                suppressed = SUPPRESSED_SENTINEL;
            } else { // Copy Throwables to new list
                suppressed = new ArrayList<>(1);
                for (Throwable t : suppressedExceptions) {
                    // Enforce constraints on suppressed exceptions in
                    // case of corrupt or malicious stream.
                    if (t == null)
                        throw new NullPointerException(NULL_CAUSE_MESSAGE);
                    if (t == this)
                        throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
                    suppressed.add(t);
                }
            }
            suppressedExceptions = suppressed;
        } // else a null suppressedExceptions field remains null

        if (stackTrace != null) {
            if (stackTrace.length == 0) {
                stackTrace = UNASSIGNED_STACK.clone();
            }  else if (stackTrace.length == 1 &&
                        // Check for the marker of an immutable stack trace
                        SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
                stackTrace = null;
            } else { // Verify stack trace elements are non-null.
                for(StackTraceElement ste : stackTrace) {
                    if (ste == null)
                        throw new NullPointerException("null StackTraceElement in serial stream. ");
                }
            }
        } else {
            stackTrace = UNASSIGNED_STACK.clone();
        }
    }

    private synchronized void writeObject(ObjectOutputStream s)
        throws IOException {
        // Ensure that the stackTrace field is initialized to a
        // non-null value, if appropriate.  As of JDK 7, a null stack
        // trace field is a valid value indicating the stack trace
        // should not be set.
        getOurStackTrace();

        StackTraceElement[] oldStackTrace = stackTrace;
        try {
            if (stackTrace == null)
                stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
            s.defaultWriteObject();
        } finally {
            stackTrace = oldStackTrace;
        }
    }

    public final synchronized void addSuppressed(Throwable exception) {
        if (exception == this)
            throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception);

        if (exception == null)
            throw new NullPointerException(NULL_CAUSE_MESSAGE);

        if (suppressedExceptions == null) // Suppressed exceptions not recorded
            return;

        if (suppressedExceptions == SUPPRESSED_SENTINEL)
            suppressedExceptions = new ArrayList<>(1);

        suppressedExceptions.add(exception);
    }

    private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];

    public final synchronized Throwable[] getSuppressed() {
        if (suppressedExceptions == SUPPRESSED_SENTINEL ||
            suppressedExceptions == null)
            return EMPTY_THROWABLE_ARRAY;
        else
            return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/85556160
今日推荐