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