-2
我想通過一個字符串,並通過一個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();
}
}
但是,當我嘗試使用的參數名稱運行它: 「健康」和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)
任何幫助將appriciated。
你可以發佈遊戲和玩家類別代碼(Game類例如實例)一個具體的對象? – zacheusz
你是什麼意思「類遊戲包含類」玩家「」我猜繼承 – zacheusz
「玩家」是一個內部類嗎? –