Example usage for java.lang Class getDeclaredFields

List of usage examples for java.lang Class getDeclaredFields

Introduction

In this page you can find the example usage for java.lang Class getDeclaredFields.

Prototype

@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException 

Source Link

Document

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

Usage

From source file:org.chorusbdd.chorus.spring.SpringContextInjector.java

private static void injectResourceFields(ApplicationContext springContext, Object handler, Class handlerClass) {
    ChorusLog log = ChorusLogFactory.getLog(SpringContextInjector.class);

    //inject handler fields with the Spring beans
    Field[] fields = handlerClass.getDeclaredFields();
    for (Field field : fields) {
        Resource resourceAnnotation = field.getAnnotation(Resource.class);
        if (resourceAnnotation != null) {
            boolean beanNameInAnnotation = !"".equals(resourceAnnotation.name());
            String name = beanNameInAnnotation ? resourceAnnotation.name() : field.getName();
            Object bean = springContext.getBean(name);
            log.trace("Found spring Resource annotation for field " + field
                    + " will attempt to inject Spring bean " + bean);
            if (bean == null) {
                log.error(/*from ww w  .ja v  a 2s . c om*/
                        "Failed to set @Resource (" + name + "). No such bean exists in application context.");
            }
            try {
                field.setAccessible(true);
                field.set(handler, bean);
            } catch (IllegalAccessException e) {
                log.error("Failed to set @Resource (" + name + ") with bean of type: " + bean.getClass(), e);
            }
        }
    }

    Class superclass = handlerClass.getSuperclass();
    if (superclass != Object.class) {
        injectResourceFields(springContext, handler, superclass);
    }
}

From source file:io.gumga.application.GumgaUntypedRepository.java

/**
 * Pegar todos os atributos de uma classe
 * @param classe objeto que voce deseja pegar os atributos
 * @return dados da pesquisa/*from w w w .  j ava  2s . c o m*/
 * @throws SecurityException
 */
public static List<Field> getTodosAtributos(Class classe) throws SecurityException {
    List<Field> aRetornar = new ArrayList<>();
    if (!classe.getSuperclass().equals(Object.class)) {
        aRetornar.addAll(getTodosAtributos(classe.getSuperclass()));
    }
    aRetornar.addAll(Arrays.asList(classe.getDeclaredFields()));
    return aRetornar;
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

@SuppressLint("DefaultLocale")
public static ArrayList<String> getNotificationText(Notification notification) {
    RemoteViews views = notification.contentView;
    Class<?> secretClass = views.getClass();

    try {//from  w w w  . j  av  a 2 s.c o m
        ArrayList<String> notificationData = new ArrayList<String>();

        Field outerFields[] = secretClass.getDeclaredFields();
        for (int i = 0; i < outerFields.length; i++) {
            if (!outerFields[i].getName().equals("mActions"))
                continue;

            outerFields[i].setAccessible(true);

            @SuppressWarnings("unchecked")
            ArrayList<Object> actions = (ArrayList<Object>) outerFields[i].get(views);
            for (Object action : actions) {
                Field innerFields[] = action.getClass().getDeclaredFields();

                Object value = null;
                for (Field field : innerFields) {
                    field.setAccessible(true);
                    // Value field could possibly contain text
                    if (field.getName().equals("value")) {
                        value = field.get(action);
                    }
                }

                // Check if value is a String
                if (value != null && value.getClass().getName().toUpperCase().contains("STRING")) {

                    notificationData.add(value.toString());
                }
            }

            return notificationData;
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public void addEntityFields(Class<? extends DalEntity> entityClass, DalResponseBuilder responseBuilder) {

    responseBuilder.addResponseMeta("SCol");

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            if (column != null) {

                DalResponseBuilder builder = responseBuilder.startTag("SCol");

                builder.attribute("Required", column.nullable() ? "0" : "1");

                int colSize = 11;
                Class<?> fieldType = fld.getType();
                if (String.class == fieldType) {
                    colSize = column.length();
                }/*from  w  w w  . j  a v a 2  s. c  o  m*/
                builder.attribute("ColSize", Integer.toString(colSize));

                builder.attribute("Description", "");

                builder.attribute("Name", column.name());

                // TODO Synchronise with the Perl DAL code
                builder.attribute("DataType", fieldType.getSimpleName().toLowerCase());

                builder.endTag();
            }
        }
    }
}

From source file:natalia.dymnikova.cluster.scheduler.impl.Codec.java

private static Object doSanitize(final Object f) {
    final Class<?> aClass = f.getClass();
    if (!isStatic(aClass.getModifiers())) {
        final Class<?> enclosingClass = aClass.getEnclosingClass();
        if (enclosingClass != null) {
            for (final Field field : aClass.getDeclaredFields()) {
                if (enclosingClass.equals(field.getType())) {
                    field.setAccessible(true);
                    try {
                        field.set(f, null);
                    } catch (final IllegalAccessException e) {
                        throw unchecked(e);
                    }//from  w  w w.  j  a  v a 2s .c  om
                }
            }
        }
    }
    return f;
}

From source file:com.test.edusys.common.utils.reflection.ReflectionUtils.java

/**
 * //from  w w w  .  j av  a2  s  . c  o  m
 */
public static List<String> getShowLogFieldName(final Class clazz) {
    List<String> lS = new ArrayList<String>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
        String filedName = f.getName();
        Annotation[] annotation = f.getAnnotations();
        for (Annotation annotation2 : annotation) {
            if (annotation2.annotationType() == ShowLog.class)
                lS.add(filedName);
        }
    }
    return lS;
}

From source file:fit.Binding.java

private static Field[] getAllDeclaredFields(Class<?> clazz) {
    if (clazz.getSuperclass() != null) {
        return (Field[]) ArrayUtils.addAll(getAllDeclaredFields(clazz.getSuperclass()),
                clazz.getDeclaredFields());
    } else {//from  ww w. jav a2 s  .co  m
        return clazz.getDeclaredFields();
    }
}

From source file:gr.abiss.calipso.tiers.specifications.GenericSpecifications.java

/**
 * Get a (cached) field for the given class' member name
 * @param clazz/*www. j a  v a2 s.c  om*/
 * @param fieldName the member name
 * @return
 */
public static Field getField(Class<?> clazz, String fieldName) {
    Field field = null;
    if (!IGNORED_FIELD_NAMES.contains(fieldName)) {

        String key = clazz.getName() + "#" + fieldName;
        field = FIELD_CACHE.get(key);

        // find it if not cached
        if (field == null && !FIELD_CACHE.containsKey(key)) {
            Class<?> tmpClass = clazz;
            do {
                for (Field tmpField : tmpClass.getDeclaredFields()) {
                    String candidateName = tmpField.getName();
                    if (candidateName.equals(fieldName)) {
                        // field.setAccessible(true);
                        FIELD_CACHE.put(key, tmpField);
                        field = tmpField;
                        break;
                    }
                }
                tmpClass = tmpClass.getSuperclass();
            } while (tmpClass != null && field == null);
        }
        if (field == null) {
            LOGGER.warn("Field '" + fieldName + "' not found on class " + clazz);
            // HashMap handles null values so we can use containsKey to cach
            // invalid fields and hence skip the reflection scan
            FIELD_CACHE.put(key, null);
        }
        // throw new RuntimeException("Field '" + fieldName +
        // "' not found on class " + clazz);
    }

    return field;
}

From source file:com.viettel.ws.client.JDBCUtil.java

public static Element createRowElement(Object obj, Document doc) {
    Element row = doc.createElement("Row");
    Class cls = obj.getClass();
    Field[] fieldArr = cls.getDeclaredFields();
    SimpleDateFormat fm = new SimpleDateFormat("dd/MM/yyyy");

    for (int i = 0; i < fieldArr.length; i++) {
        try {//from  w  w w . j a  v  a  2s  .  co m
            String fieldName = fieldArr[i].getName();
            String getMethodName = "get" + UpcaseFirst(fieldName);
            Method getMethod = cls.getMethod(getMethodName);

            Object value = getMethod.invoke(obj);
            if (fieldArr[i].getType().equals(Date.class)) {
                value = fm.format(value);
            }

            Element node = doc.createElement(convertToOrigin(fieldName));
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);

        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            continue;
        }
    }
    return row;
}

From source file:app.commons.ReflectionUtils.java

public static Field[] getAllDeclaredFields(Class clazz) {
    Class currentClass = clazz;
    List<Field> fields = new ArrayList<Field>();
    while (currentClass != null) {
        fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
        currentClass = currentClass.getSuperclass();
    }/* w w  w  .  j ava2s . c  o m*/
    return fields.toArray(new Field[fields.size()]);
}