get declared Field from class by name - Android java.lang.reflect

Android examples for java.lang.reflect:Field Name

Description

get declared Field from class by name

Demo Code

/*/*from   w  w  w .  j a va 2s  .c  o  m*/
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 * 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.
 */
//package com.java2s;
import java.lang.reflect.Field;

public class Main {
    public static Object getField(final Class clazz,
            final String fieldName, final Object object) throws Exception {
        try {
            final Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);

            return field.get(object);
        } catch (final Exception e) {
            final String msg = String.format(
                    "error while getting field %s from object %s",
                    fieldName, object);
            throw new Exception(msg, e);
        }
    }

    public static Object getField(final String field, final Object object)
            throws Exception {
        return getField(object.getClass(), field, object);
    }

    public static Object getField(final String className,
            final String field, final Object object) throws Exception {
        return getField(getClass(className), field, object);
    }

    public static Class getClass(final String name) throws Exception {
        try {
            return Class.forName(name);
        } catch (final ClassNotFoundException e) {
            final String msg = String.format("unable to find class %s",
                    name);
            throw new Exception(msg, e);
        }
    }
}

Related Tutorials