Leon Armstrong
Leon Armstrong

Reputation: 1303

How to access the instance while using reflection?

I have a class that loop through an instance's member at run-time.

Below is a class that contain different field with different type. AssetTexture is one of the type I wanted to loop through.

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;

}

Below is the sample code of AssetTexture class. It only contain a name.

class AssetTexture {

    private String name;

    public AssetTexture(String name){
        this.name=name;
    }

}

Below is the method I use to loop through all field at runtime. It is successful. But I have try all available method of field. It doesn't have the method to get the member.

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());
        }
    }

}

Current output:

T_BG
T_LOGO
T_REELS

Expected result:

bg.png
reels.png
logo.png

I have tried to use the toString method and overide toString in AssetTexture. Like the code below

field.getName() ---> field.toString()

overrided toString in AssetTexture

class AssetTexture {

    @Override
    public String toString() {return name;}

}

But it doesn't run the override method.

Upvotes: 0

Views: 44

Answers (1)

Leo Aso
Leo Aso

Reputation: 12463

Instead of calling field.getName(), call field.get(null).toString(). Field.get returns the field's value for a particular instance, and for static fields, the instance is not required so you can pass null.

Upvotes: 2

Related Questions