1

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

2
  • 2
    You probably could in that specific scenario using a getter or reflection. How about HashMapping your TextureRegions to string keys in a map? String for a key, TextureRegion for a value? Commented Jul 26, 2011 at 20:21
  • Not in Java. You can in Groovy and other languages Commented Jul 26, 2011 at 20:21

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

this works well it just throws a lot of exceptions which need surrounded with try catch's
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.