java - 如何使用反射返回二维数组?

标签 java arrays

代码的用途

通过将图片与 DataStoragePics 类中已存在的一组像素进行比较,找出屏幕上的图片,这些像素采用返回二维数组的方法形式。

我是如何尝试解决它的

  1. 使用反射,我将 DataStoragePics 类中的所有方法存储在 methodStorage[] 中。
  2. 然后我从 methodStorage[] 调用一个方法,该方法随后将存储在 tempMatrix[][] 中。
  3. 我稍后将使用循环和另一种方法(此处未显示)来找出捕获的像素集是什么类型的图片。

我需要什么帮助

当我尝试使用上述步骤解决问题时,我在主类底部的第三行重复了两次错误:

Multiple markers at this line - Type mismatch: cannot convert from Object to int.

我认为问题是 methodStorage[x].invoke(DataStoragePicsObj) 是一个单一的数组,但它返回一个二维数组并且程序无法识别,所以它需要 tempMatrix 是一个简单的数组,或者 methodStorage[] 是一个二维数组。我需要帮助解决该错误。

这是 Main 类:

import java.lang.reflect.Method;

  int [][] tempMatrix = new int[16][450];

//Creates a DataStoragePics Object.
  DataStoragePics DataStoragePicsObj = new DataStoragePics();
//Stores all DataStoragePics methods in methods[].
  Method[] methodStorage = DataStoragePicsObj.getClass().getMethods();

//Loops through methodStorage[].
  for(int x = 0; x < method.length; x++)
  {
      //Stores a 2D array from DataStoragePics class in tempMatrix.
      //All methods in DataStoragePics return a 2D array with [16][10] dimensions.

      /*This is the error line*/ 
      tempMatrix[16][10] = methodStorage[x].invoke(DataStoragePicsObj);
      /*above is the error line*/
  }

这是 DataStoragePics 类的一部分:

public class DataStoragePics
{

  public int[][] picXYZ()
    {
      int[][] rgbValues = 
      {
        {1,2,3,4},
        {9,8,7,6}
      };

      return rgbValues;
    }
}

在 java/编码方面,我有点初学者,所以请不要使用复杂的术语。

教学大纲的回答有帮助,但我仍然收到此错误:“线程“主”java.lang.ClassCastException 中的异常:java.lang.Class 无法转换为 [[I”并返回屏幕上的东西。有时它在最后有时在中间显示错误。不知道为什么。

最佳答案

您正在遍历类中的所有 方法。并将每个方法的返回值转换为 int[][] .

Method[] methodStorage = DataStoragePicsObj.getClass().getMethods();

//Loops through methodStorage[].
  for(int x = 0; x < method.length; x++)

这当然会失败,因为你的 DataStoragePicsObj类隐式扩展 java.lang.Object它有类似 hashCode 的方法, toStringgetClass不返回 int[][] .

如果你通过反射调用一个方法,你应该准备好将正确的参数传递给它并处理它的返回值;如果不能,则不应通过反射调用该方法。

你可以做的 - 如果我对你想做的事情的理解是正确的 - 检查返回类型和参数以确保你准备好处理反射调用:

    Method m = methodStorage[x];
    if (m.getReturnType() != int[][].class || m.getParameterTypes().length != 0) {
        // Skip this method because it requires arguments or doesn't return int[][]
        continue;
    }

关于java - 如何使用反射返回二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251310/

相关文章:

php - 配置 2d php 数组

java - 从Java中的文本文件中读取特定行

java - 使用 Cucumber 中的 AssertJ Swing 测试

java - 用于过滤的 For-Each 循环的替代品是什么?

java - 如何模拟 Spring SecurityContext 以便我可以将它与 TestNG 一起使用?

java - 将 Account 对象添加到 ArrayList

javascript - react /JSX : Iterating through an object with key/value pairs

javascript - 如何使用 JSON 将数组从 Twig 传递到 Javascript

javascript - 小写并连接数组内容(给定常量除外)的最佳方法

c++ - C++ 中 vector 下标超出范围