実行時にインスタンスのメンバーをループするクラスがあります。リフレクションの使用中にインスタンスにアクセスするにはどうすればよいですか?
以下は、異なるタイプの異なるフィールドを含むクラスです。 AssetTextureは、ループしたいタイプの1つです。
public class A {
public static AssetTexture T_BG = new AssetTexture("bg.png");
public static AssetTexture T_REELS = new AssetTexture("reels.png");
public static AssetTexture T_LOGO = new AssetTexture("logo.png");
public static String things_that_should_not_inside_the_loop;
}
以下は、AssetTextureクラスのサンプルコードです。それは名前だけを含んでいます。
class AssetTexture {
private String name;
public AssetTexture(String name){
this.name=name;
}
}
以下は、実行時にすべてのフィールドをループするために使用する方法です。それは成功です。しかし、私はフィールドのすべての利用可能な方法を試してみました。メンバーになる方法はありません。
public class Manager {
public Manager(){
A a=new A();//init A
//loop through all field of instance a
Field[] fields=this.a.getClass().getDeclaredFields();
for(Field field:fields){
if(field.getType().equals(AssetTexture.class)){
Gdx.app.debug("Debug", field.getName());
}
}
}
電流出力:
T_BG
T_LOGO
T_REELS
期待される結果:
bg.png
reels.png
logo.png
私はAssetTextureでのtoStringメソッドとオーバライドのtoStringを使用しようとしました。 AssetTexture
class AssetTexture {
@Override
public String toString() {return name;}
}
で
field.getName() ---> field.toString()
オーバーライドのtoString以下のコードのようなしかし、それはオーバーライドメソッドを実行しません。
今、フィールド名を受け取りました。 '(String)field.get(a)'を使用してください。 https://stackoverflow.com/a/17461487/5449250をご覧ください。 –