简体   繁体   中英

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

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.

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

您可以使用Java Reflection API访问基于变量的类的静态字段。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM