001/*
002 * SonarQube
003 * Copyright (C) 2009-2017 SonarSource SA
004 * mailto:info AT sonarsource DOT com
005 *
006 * This program is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.api.utils;
021
022import org.apache.commons.lang.ClassUtils;
023
024import java.lang.reflect.Field;
025import java.lang.reflect.Modifier;
026import java.util.ArrayList;
027import java.util.Collections;
028import java.util.List;
029
030/**
031 * Add features missing in {@code org.apache.commons.lang.reflect.FieldUtils}.
032 *
033 * @since 2.14
034 */
035public final class FieldUtils2 {
036  private FieldUtils2() {
037    // only statics
038  }
039
040  /**
041   * Get accessible {@code Field} breaking scope if requested. Superclasses/interfaces are considered.
042   *
043   * @param clazz       the class to reflect, must not be null
044   * @param forceAccess whether to break scope restrictions using the {@code setAccessible} method.
045   *                    {@code False} only matches public fields.
046   */
047  public static List<Field> getFields(Class clazz, boolean forceAccess) {
048    List<Field> result = new ArrayList<>();
049    Class c = clazz;
050    while (c != null) {
051      for (Field declaredField : c.getDeclaredFields()) {
052        if (!Modifier.isPublic(declaredField.getModifiers())) {
053          if (forceAccess) {
054            declaredField.setAccessible(true);
055          } else {
056            continue;
057          }
058        }
059        result.add(declaredField);
060      }
061      c = c.getSuperclass();
062    }
063
064    for (Object anInterface : ClassUtils.getAllInterfaces(clazz)) {
065      Collections.addAll(result, ((Class) anInterface).getDeclaredFields());
066    }
067
068    return result;
069  }
070}