代码的目的
要了解屏幕上的图片,请将其与DataStoragePics类中已经存在的像素集合进行比较,这些像素以返回2D数组的方法的形式出现。
我是如何解决这个问题的
DataStoragePics类中的所有方法存储在methodStorage[]中。methodStorage[]调用一个方法,该方法将存储在一个tempMatrix[][]中。我需要的帮助
当我试图使用上面提到的步骤来解决这个问题时,我从主类的底部得到了一个错误,重复了两次:
此行中的多个标记类型不匹配:无法从对象转换为int。
我认为问题在于methodStorage[x].invoke(DataStoragePicsObj)是一个单一数组,但是它返回一个2D数组,程序不认识到这一点,所以它需要tempMatrix作为一个简单数组,或者methodStorage[]需要一个2D数组。我需要帮助解决那个错误。
这是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]--这个东西正在转换,它在屏幕上存储和返回内容。有时它在结尾处显示错误,有时在中间。不知道为什么,
发布于 2014-12-06 03:17:56
您正在循环遍历类中的所有方法。并将每个方法的返回值转换为int[][]。
Method[] methodStorage = DataStoragePicsObj.getClass().getMethods();
//Loops through methodStorage[].
for(int x = 0; x < method.length; x++)这当然会失败,因为您的DataStoragePicsObj类隐式地扩展了java.lang.Object,其中包含不返回int[][]的方法,如hashCode、toString和getClass。
如果通过反射调用方法,则应该准备传递正确的参数及其返回值的进程;如果不能,则不应该通过反射调用该方法。
如果我对您想要做的事情的理解是正确的,那么您可以做的是检查返回类型和参数,以确保您准备好处理反射调用:
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;
}发布于 2014-12-02 14:58:38
实际上,在没有“强制转换”的情况下,编译器只考虑invoke返回一个Object。
tempMatrix[16][10]表示tempMatrix数组中的元素(16,10),因此它的类型是int。
因此,将对象分配给int会引发编译器错误:在"=“后面的类型必须是”相同“。
首先,必须将调用返回的对象转换为int[][]。然后必须分配给一个int对象(完整的tempMatrix?)
tempMatrix = (int[][]) methodStorage[x].invoke(DataStoragePicsObj);https://stackoverflow.com/questions/27251310
复制相似问题