簡體   English   中英

如何在不知道Java中的維度的情況下強制轉換多維數組

[英]How to cast a multidimensional array without knowing the dimension in Java

有一個多維String數組作為Object傳入。
我應該“展開”它並處理每個原始條目。 除了通過查看Object本身之外,無法知道維度。

我遇到的困難在於鑄造。 我可以通過調用它的getClass().getName()並計算[ -s那里來查找數組維度。

但那么如何施展呢?

String[] sa = (String[]) arr;

正在給予

Exception in thread "main" java.lang.ClassCastException: [[Ljava.lang.String; cannot be cast to [Ljava.lang.String;

這種鑄造可以在不使用反射的情況下完成嗎?

注 - 數組可以是任何維度 - 不只是1或2。

TIA。

如果你想使用一個在編譯時不知道哪個維度的數組,我建議你遞歸處理它的所有條目而不是試圖強制轉換它。

您可以使用object.getClass().isArray()方法檢查當前條目是否為數組,然后使用Array.getLength(object)Array.get(object, i)迭代它:

public static void main(String[] args) {
    Object array = new String[][] {new String[] {"a", "b"}, new String[] {"c", "d"}};
    processArray(array, System.out::println);
}

public static void processArray(Object object, Consumer<Object> processor) {
    if (object != null && object.getClass().isArray()) {
        int length = Array.getLength(object);
        for (int i = 0; i < length; i ++) {
            Object arrayElement = Array.get(object, i);
            processArray(arrayElement, processor);
        }
    } else {
        processor.accept(object);
    }
}

如果數組的大小不是靜態知道的(在編譯時),那么邏輯上不可能僅依靠靜態方法獲得長度,即不使用動態方法。

也許這個問題有你需要的解決方案: 使用反射在Java數組中獲取字段“length”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM