Java tutorial
//package com.java2s; /* This file is part of Roboject Copyright (c) 2010-2011 akquinet A.G. Contact: http://www.akquinet.de/en Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import android.content.Context; import java.lang.reflect.Field; public class Main { /** * Check application's R.id class and retrieve the value of the static * member with the given name. */ public static int getIdentifierFromR(Context context, String type, String name) { Class<?> rClass = null; try { rClass = Class.forName(context.getPackageName() + ".R$" + type); } catch (ClassNotFoundException e) { // No R.id class? This should never happen. throw new RuntimeException(e); } try { Field rField = rClass.getField(name); Object intValue; try { intValue = rField.get(null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (!(intValue instanceof Integer)) { throw new RuntimeException("Not an int: " + rClass.getCanonicalName() + "." + rField.getName()); } return ((Integer) intValue).intValue(); } catch (NoSuchFieldException e) { throw new RuntimeException("There is no such id in the R class: " + context.getPackageName() + ".R." + type + "." + name + ")"); } catch (SecurityException e) { throw new RuntimeException(e); } } }