001    /*
002     * SonarQube, open source software quality management tool.
003     * Copyright (C) 2008-2014 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * SonarQube 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     * SonarQube 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     */
020    package org.sonar.api.utils;
021    
022    import com.google.common.collect.Lists;
023    import org.apache.commons.lang.ClassUtils;
024    
025    import java.lang.reflect.Field;
026    import java.lang.reflect.Modifier;
027    import java.util.Collections;
028    import java.util.List;
029    
030    /**
031     * Add features missing in org.apache.commons.lang.reflect.FieldUtils
032     *
033     * @since 2.14
034     */
035    public final class FieldUtils2 {
036      private FieldUtils2() {
037      }
038    
039      /**
040       * Get accessible <code>Field</code> breaking scope if requested. Superclasses/interfaces are considered.
041       *
042       * @param clazz       the class to reflect, must not be null
043       * @param forceAccess whether to break scope restrictions using the <code>setAccessible</code> method.
044       *                    <code>False</code> only matches public fields.
045       */
046      public static List<Field> getFields(Class clazz, boolean forceAccess) {
047        List<Field> result = Lists.newArrayList();
048        Class c = clazz;
049        while (c != null) {
050          for (Field declaredField : c.getDeclaredFields()) {
051            if (!Modifier.isPublic(declaredField.getModifiers())) {
052              if (forceAccess) {
053                declaredField.setAccessible(true);//NOSONAR only works from sufficiently privileged code
054              } else {
055                continue;
056              }
057            }
058            result.add(declaredField);
059          }
060          c = c.getSuperclass();
061        }
062    
063        for (Object anInterface : ClassUtils.getAllInterfaces(clazz)) {
064          Collections.addAll(result, ((Class) anInterface).getDeclaredFields());
065        }
066    
067        return result;
068      }
069    }