Java判断对象类型是否为数组

判断对象是否为数组:

public static void main(String[] args) {
        String[] a = ["1","2"];

        if(a instanceof String[]){
            System.out.println("ss")
        }

        if(a.getClass().isArray()){
            System.out.println("yy")
        }
    }

第一种做法:instanceof

java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
 用法:
result = object instanceof class
参数:
Result:布尔类型。
Object:必选项。任意对象表达式。
Class:必选项。任意已定义的对象类。

第二种做法:Class类 isArray()

/**
* Determines if this {@code Class} object represents an array class.
*
* @return {@code true} if this object represents an array class;
* {@code false} otherwise.
* @since JDK1.1
*/
public native boolean isArray();

欢迎关注Java流水账公众号
原文地址:https://www.cnblogs.com/guofu-angela/p/9078098.html