-2

次のように、文字列を介してクラスを取得し、文字列配列を介してクラスへのパスを取得しようとしています。

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)

どんな助けでも感謝します。

4

1 に答える 1

1

void メソッドであり、値を返そうとしているため、投稿したコードに構文エラーがあるようです。

エラーログによると、呼び出し時に int 値を返そうとしていると思います

return f.get(current)

ただし、変数currentはフィールド f を含むクラスのインスタンスではなく、クラス オブジェクトです。つまり、Game クラスまたはループ内で一致する他のクラスへの参照です。

機能させるにはcurrent、具体的なオブジェクト (たとえば、Game クラスのインスタンス) を指す必要があります。

于 2013-07-04T23:48:41.697 に答える