Android examples for java.lang.reflect:Field Name
Attempt to find a java.lang.reflect.Field field on the supplied Class with the supplied name.
/*//from ww w . jav a 2 s. c o m * Copyright 2002-2009 the original author or authors. * * 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 java.lang.reflect.Field; public class Main { /** * Attempt to find a {@link java.lang.reflect.Field field} on the supplied * {@link Class} with the supplied <code>name</code>. Searches all * superclasses up to {@link Object}. * * @param clazz * the class to introspect * @param name * the name of the field * @return the corresponding Field object, or <code>null</code> if not found */ public static Field findField(Class<?> clazz, String name) { return findField(clazz, name, null); } /** * Attempt to find a {@link java.lang.reflect.Field field} on the supplied * {@link Class} with the supplied <code>name</code> and/or {@link Class type} * . Searches all superclasses up to {@link Object}. * * @param clazz * the class to introspect * @param name * the name of the field (may be <code>null</code> if type is * specified) * @param type * the type of the field (may be <code>null</code> if name is * specified) * @return the corresponding Field object, or <code>null</code> if not found */ public static Field findField(Class<?> clazz, String name, Class<?> type) { Class<?> searchType = clazz; while (!Object.class.equals(searchType) && searchType != null) { Field[] fields = searchType.getDeclaredFields(); for (Field field : fields) { if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { return field; } } searchType = searchType.getSuperclass(); } return null; } }