Here you can find the source of findField(final Class> clazz, final String name, final Class> type)
name
and/or Class type .
Parameter | Description |
---|---|
clazz | The class to introspect |
name | The name of the field (may be <code>null</code> if type is specified) |
type | The type of the field (may be <code>null</code> if name is specified) |
public static Field findField(final Class<?> clazz, final String name, final Class<?> type)
//package com.java2s; /*/*from w w w . j a va 2 s.c om*/ * Copyright (C) 2011 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 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 */ public static Field findField(final Class<?> clazz, final String name, final Class<?> type) { if (clazz == null) { throw new IllegalArgumentException("Class must not be null"); } if (name == null && type == null) { throw new IllegalArgumentException("Either name or type of the field must be specified."); } 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(); } throw new IllegalArgumentException( "Unable to find " + (type != null ? type.getName() : "") + " " + (name != null ? name : "") + "."); } }