我正在尝试通过 String 获取类,并通过 String 数组获取类的路径,如下所示:
public void getClass(String name, String[] className){
try {
Class current=Game.class;
if(className!=null)
for(int i2=0;i2<className.length;i2++){
for(int i=0;i<current.getClasses().length;i++){
if(className[i2].equals(current.getClasses()[i].getSimpleName())){
current=current.getClasses()[i];
System.out.println(current.getSimpleName());
break;
}
}
}
Field f=current.getDeclaredField(name.trim());
f.setAccessible(true);
return f.get(current);
} catch (Exception e) {
e.printStackTrace();
}
}
但是当我尝试使用参数 name:"health" 和 className:{"player"} 运行它时,它应该可以工作,因为 Game 类包含类“player”,而 player 包含整数“health”。相反,我收到此错误消息:
java.lang.IllegalArgumentException: Can not set int field Game.Game$Player.health to java.lang.Class
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(Unknown Source)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at Game.Game$Enemy.callVariable(Game.java:1384)
at Game.Game$Enemy.callMethods(Game.java:1357)
at Game.Game$Enemy.update(Game.java:1295)
at Game.Game$EnemyContainer.update(Game.java:1235)
at Game.Game.doFrameInGame(Game.java:563)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
任何帮助都将不胜感激。