Chris
Chris

Reputation: 1766

Java: Static access using a string?

Wasnt too sure on the title for the but I have a file that is used to retrieve certain texture coordinates. The file is called Assets and just contains a bunch of items like what is below...

public static TextureRegion level1;

To get access to this I just use Assets.level1 for another part of the program and thats that.

What I'm wondering is if there is a way to do this through a string, for example instead of Assets.level2 i could do something like Assets.(string) where string = "level2"

Any help will be great

Upvotes: 1

Views: 234

Answers (3)

Jack Edmonds
Jack Edmonds

Reputation: 33171

You can access static fields of a class based on a variable by using the Java Reflection API.

TextureRegion lvl = (TextureRegion) Assets.class.getDeclaredField("level1").get(null);

Upvotes: 0

Roman Zenka
Roman Zenka

Reputation: 3604

(TextureRegion)Assets.class.getField("level2").get(null)

Upvotes: 2

Etienne de Martel
Etienne de Martel

Reputation: 36851

Instead of having those as static fields in the Assets class, you should add a static method to Assets:

public static TextureRegion getTextureRegion(String name)
{
    // get it somehow
}

Now, for the "somehow" part: the easiest (and most flexible) way would be to have a Map<String, TextureRegion> (Map is an interface, HashMap would probably be sufficient in this case) in your Assets class that contains the texture regions. How you put data in that map is up to you. For instance:

regions.put("level1", your_level_1_region);

Then, your getTextureRegion becomes:

public static TextureRegion getTextureRegion(String name)
{
    return regions.get(name);
}

The upside of this is that those regions could be determined at runtime (perhaps loaded from a file) instead of being hardcoded.

Upvotes: 4

Related Questions