【发布时间】:2018-02-11 15:50:10
【问题描述】:
我正在尝试转换此数据类型,以便稍后在另一个类中调用该方法,以通过具有@987654323 字段的类的索引号来切换在其他方法中进行的布局,例如recipe1Layout(); @数组。
这里是getItem()方法
public int getItem(){
int index = 0;
for(int i = 0; i < 100; i++) {
try{
index = recipe.getClass().getField("Classes").get(i);
} catch(Exception e){
}
}
return index;
}
这是配方类
public class Recipes {
public Class<?>[] Classes = {
ChileConLecheActivity.class,
ArrozActivity.class,
EnchiladasActivity.class,
SopaActivity.class
};
}
Class 的类型需要在这里,因为我对 recipe 类还有其他用途。
例如,创建一个所有类的新实例,以便稍后调用以使用一种方法对所有类进行调整。
我唯一能想到的就是将类型 Class 转换为 int,这样我就可以调用返回索引号的方法,我可以执行类似配方的操作。
index = Integer.parseInt(Classes[I].getName().toString());
但这是我寻求帮助的地方,我不知道如何摆脱 logcat 中的错误。
错误显示为
IndexOutOfArrayException
【问题讨论】:
-
int是一个原语。你需要转换成Integer.class,也就是Class<?> -
您的错误是
I >= Classes.length,但您没有向我们展示I的分配对象。而Integer.parseInt()将无法解析"ChileConLecheActivity",所以你的问题没有意义...... -
您是在问如何在类数组中找到特定类的索引?
-
同意 cricket_007。这有 XY 问题的迹象。您正在尝试执行任务 X,并且您已经找到了一个虚假的解决方案 Y。Y 不起作用(因为它是虚假的)但是由于您没有解释任务 X,我们无法告诉您什么 Z(真正的解决方案) 可能是。 meta.stackexchange.com/questions/66377/what-is-the-xy-problem
-
您可以尝试使用
HashMap<Class<?>,Integer>代替数组。
标签: java android types type-conversion indexoutofboundsexception