Java 是否可以通过反射提供变量名来使用变量?
我试图在运行时访问R.java类中生成的一些字符串资源Java 是否可以通过反射提供变量名来使用变量?,java,android,Java,Android,我试图在运行时访问R.java类中生成的一些字符串资源 String current = getStringId(); Resources res = context.getResources(); // Must provide an Activity or Context object here int resourceId = res.getIdentifier(current, "string", context.getPackageName()); // Do whatever wi
String current = getStringId();
Resources res = context.getResources(); // Must provide an Activity or Context object here
int resourceId = res.getIdentifier(current, "string", context.getPackageName());
// Do whatever with resourceId
R.java:
public static final class string {
public static final int app_name=0x7f040000;
public static final int eightOvereight=0x7f040030;
public static final int eightOvernine=0x7f040031;
public static final int fiveOvereight=0x7f040027;
public static final int fiveOverfive=0x7f040024;
public static final int fiveOvernine=0x7f040028;
public static final int fiveOverseven=0x7f040026;
public static final int fiveOversix=0x7f040025;
public static final int fourOvereight=0x7f040022;
public static final int fourOverfive=0x7f04001f;
{
在运行时,我有:
String current = getStringId(); // assume current = "eightOvereight" after this line
//now I would like to use R.string.eightOvereight. I don't want to use a switch statement.
我可以通过反射来实现吗?如果应用程序不需要反射,那么使用反射实际上不是一个好主意。在运行时,您可以根据条件(屏幕大小、API版本、语言环境等)在不同的文件夹中定义具有适当名称的资源,从而获得不同的资源 尽可能避免反思。还可以将
getStringId()
值分配给字符串变量,该值应为int
String current = getStringId();
是的,这是可能的。但是使用反射来实现这一点是混乱的、复杂的、低效的和潜在的脆弱的 最好使用
HashMap
进行查找;e、 g.假设您需要这些变量作为静态变量存在,然后添加以下内容:
private static Map<String, Integer> MAP = new Map<String, Integer> {{
put("eightOvereight", eightOvereight);
put("eightOvernine", eightOvernine);
....
}
私有静态映射=新映射{{
put(“eightOvereight”,eightOvereight);
put(“八维宁”,八维宁);
....
}
然后使用MAP.get(str)
获取值
注意-这是一个通用的Java解决方案。@Eric的回答提供了一个更好的特定于Android的解决方案。您可以使用反射,但是……不要使用反射。它应该只在非常非常罕见的情况下使用。这不是其中之一 Android提供了一种在运行时选择可变资源的机制
String current = getStringId();
Resources res = context.getResources(); // Must provide an Activity or Context object here
int resourceId = res.getIdentifier(current, "string", context.getPackageName());
// Do whatever with resourceId
您可能需要查找。[Class::getField](是您要查找的内容。“是”.Step#1将是搜索此任务。-1因为您知道机制,但什么也不带:
android access变量反射
似乎是一个非常直接的搜索。这是一个很好的建议,但它看起来更像是一个注释而不是答案;它实际上根本没有回答OP的问题。除了android将重新生成如果资源被修改,那么在另一个构建中的静态id…实际上,这些id可以更改(您的映射值),所以它甚至比脆弱的方法更脆弱。