簡體   English   中英

Java:使用通用 class 進行反射的幫助(和審查)

[英]Java: Help (and review) with reflection with Generic class

我正在創建一個具有泛型類型的矩陣 class (僅用於實驗)

import java.lang.reflect.Array;
import java.util.Arrays;

@SuppressWarnings("unused")
public class Matrix<T extends Number> {
  private int nRow;
  private int nCol;
  private T[] elements;
  private T[][] elementsGrid;

  public Matrix(int nRow, T[] elements) {
    this(nRow, nRow, elements);
  }

  public Matrix(int nRow, int nCol, T[] elements) {
    if (elements.length != nRow * nCol) {
      throw new IllegalArgumentException(
          "Incorrect size: Expected(" + nRow * nCol + "), but provided(" + elements.length + ")");
    }
    this.nRow = nRow;
    this.nCol = nCol;
    this.elements = elements;

    @SuppressWarnings("unchecked")
    T[][] t = (T[][]) Array.newInstance(elements.getClass().getComponentType(), new int[] { nRow, nCol });

    elementsGrid = t;
    for (int i = 0; i < nRow; i++) {
      for (int j = 0; j < nCol; j++) {
        elementsGrid[i][j] = elements[i * nCol + j];
      }
    }
    System.out.println(Arrays.deepToString(elementsGrid));

  }

基本上我只是把一個單調暗陣列復制到雙暗陣列。 代碼工作正常,但我不得不為此付出很多努力,我不確定這是否確實是處理這個問題的正確方法。 例如,如果我刪除@SuppressWarnings("unchecked"),它會給我警告,未經檢查的演員表。 是否可以忽略此警告,因為我已經聲明我的泛型只允許Number的子類。

Class.getComponentTypeArray.newInstance都有點原始。 你只能這樣做:

Object[][] t = (Object[][]) Array.newInstance(elements.getClass().getComponentType(),
                             nRow, nCol); // Object is actually type T.

但這實際上在形式上是錯誤的。 應該是T。所以你的版本並不差。

看這個:

int[][] t = (int[][]) Array.newInstance(int.class, nRow, nCol);

generics 不可行。

對於運行時演員表:

Class<?> ctype = elements.getClass().getComponentType();
ctype.cast(object);

似乎有一個改進:

// Array:
static <C> C[] newInstance​(Class<C> componentType, int length);

Unfortunately you also can have int.class besides Integer.class for int[].class and Integer.class .

java 中打字系統的語言手段並沒有形成一個完整的“代數”來描述這一切。

然而,再過幾年我們就會看到List<int>

同時,要么尋找更完整的語言,要么嘗試使用ArrayList<T>代替T[] ,並使用顯式Class<T> componentType來表示缺少的 getComponentType()。

暫無
暫無

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

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