Search code examples
javaandroidreflectionintrospection

is there any way to inspect a variable's label in java?


int foo = 0xff;

String label = getNameOfFoo(foo);

System.out.println(label);// this should print "foo";

private String getNameOfFoo(int n){
  String ret;

  ///WHAT COULD I DO HERE TO MAKE THIS A REALITY?

  return ret;
}

Before you jump on me with "Why in GOD'S name would you need this?!" I will say that my goal is get around Android's mechanism of identifying my View id's as strings (ie. "id=@+id/user_name") but having to get it back in my code as int user_name = R.id.user_name. This works fine when I know that there is a "user_name" label. But goes to crap when I don't. I'm trying to write a skinnable app that may or may not contain all sorts of things in the xml, and I need a way to inspect the ids as strings.


Solution

  • You can use Context.getResources() for this.

    int resID = getResources().getIdentifier("label_name", "drawable", "com.test.app");
    

    And the returned resID. If it's 0 then the label is not found. Read here for more about Resources.