Android examples for java.lang.reflect:Field Name
get Object By Field Name
/*/*from w ww .j ava2 s . c o m*/ * Copyright 2014-2016 QuickAF * * 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.text.TextUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class Main{ @SuppressWarnings("unchecked") public static <T> T getObjectByFieldName(Object object, String fieldName, Class<T> clas) { if (object != null && !TextUtils.isEmpty(fieldName) && clas != null) { try { Field field = ReflectUtils.getField(object.getClass(), fieldName, true, true); if (field != null) { field.setAccessible(true); return (T) field.get(object); } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } else { return null; } } public static Field getField(Class<?> sourceClass, String fieldName, boolean isFindDeclaredField, boolean isUpwardFind) { Field field = null; try { field = isFindDeclaredField ? sourceClass .getDeclaredField(fieldName) : sourceClass .getField(fieldName); } catch (NoSuchFieldException e1) { if (isUpwardFind) { Class<?> classs = sourceClass.getSuperclass(); while (field == null && classs != null) { try { field = isFindDeclaredField ? classs .getDeclaredField(fieldName) : classs .getField(fieldName); } catch (NoSuchFieldException e11) { classs = classs.getSuperclass(); } } } } return field; } public static Field getField(Class<?> sourceClass, String fieldName) { return getField(sourceClass, fieldName, true, true); } }