What is the purpose of java.lang.reflect.Array's getter and setter methods?

前端 未结 3 1628
执笔经年
执笔经年 2021-02-09 18:03

Java Class java.lang.reflect.Array provides a set of tools for creating an array dynamically. However in addition to that it has a whole set of methods for accessing (get, set,

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-09 19:09

    This class is quite esoteric - most uses of arrays know the type of the array, so this class is typically most useful when implementing code that handles arrays generically.

    There is no array superclass for all arrays, so there is no uniform way of accessing elements or the size of an array regardless of type. The java.lang.reflect.Array fills this gap and allows you to access the array in the same way regardless from type. For example, to get the value at a given index from any array (returned as an object).

    It's parameteric polymorphism. Sure, you could code this yourself if you know the type - you just cast. If you don't know the array type, or it can be several types, you would check the possibilities and cast appropriately - which is what the code in reflect.Array does.

    EDIT: In response to the comment. Consider how you would solve this problem - how to count the number of times a value is duplicated in an array. Without the type-agnostic Array class, this would not be possible to code, without explicitly casting the array, so you would need a different function for each array type. Here, we have one function that handles any type of array.

    public Map countDuplicates(Object anArray)
    {
        if (!anArray.getClass().isArray())
            throw new IllegalArgumentException("anArray is not an array");
    
        Map dedup = new HashMap();
        int length = Array.getLength(anArray);
        for (int i=0; i

    EDIT2: Regarding the get*() and set*() methods. The source code link above links to Apache harmony. The implementation there does not adhere to the Sun Javadocs. For example, from the getInt method

    @throws IllegalArgumentException If the specified object is not an array, 
    or if the indexed element cannot be converted to the return type 
    by an identity or widening conversion 
    

    This implies that the actual array could be byte[], short[] or int[]. This is not the case with the Harmony implementation, which only takes an int[]. (Incidentally, the Sun implementation uses native methods for most of the Array class.) The get*() and set*() methods are there for the same reason as get(), getLength() - to provide (loosely) type-agnostic array access.

    Not exactly something you need to use every day, but I imagine it provides value for those that need it.

提交回复
热议问题