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:IntrospectionUtil.java

public static boolean containsSameFieldName(Field field, Class c, boolean checkPackage) {
    if (checkPackage) {
        if (!c.getPackage().equals(field.getDeclaringClass().getPackage()))
            return false;
    }//from  w w w.j a v  a  2 s . co  m

    boolean sameName = false;
    Field[] fields = c.getDeclaredFields();
    for (int i = 0; i < fields.length && !sameName; i++) {
        if (fields[i].getName().equals(field.getName()))
            sameName = true;
    }
    return sameName;
}

From source file:com.palantir.ptoss.util.Reflections.java

/**
 * Find a {@link Field} based on the field name.  Will return private fields but will not
 * look in superclasses.//w ww  .  j  a va2 s.  co m
 *
 * @return null if there is no field found
 */
// TODO (dcervelli) fix for superclasses
public static Field getFieldByName(Class<?> klass, String fieldName) {
    for (Field f : klass.getDeclaredFields()) {
        if (f.getName().equals(fieldName)) {
            return f;
        }
    }
    return null;
}

From source file:com.aw.core.cache.loader.MetaLoader.java

/**
 * Busca en la instancia Atributos del tipo {@link com.aw.core.cache.loader.MetaLoader}
 *//*w w  w. j  a v a  2  s .  c o  m*/
static public List<MetaLoader> find(Object instance) {
    List<MetaLoader> list = new ArrayList<MetaLoader>();

    Class cls = instance.getClass();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        try {
            Object value = field.get(instance);
            if (value instanceof MetaLoader)
                list.add((MetaLoader) value);
        } catch (IllegalAccessException e) {
            throw AWBusinessException.wrapUnhandledException(logger, e);
        }
    }
    return list;
}

From source file:com.zhuangjy.dao.ReflectionUtil.java

private static void getFieldsByAnnotation(List<Field> list, Class<? extends Annotation> annotation, Class clz) {
    if (clz.equals(Object.class)) {
        return;/*from  w  w w  .ja va2 s  . c  om*/
    }
    Field[] fields = clz.getDeclaredFields();
    if (fields == null || fields.length == 0) {
        return;
    }
    for (Field f : fields) {
        f.setAccessible(true);
        if (f.getAnnotation(annotation) != null) {
            list.add(f);
        }
    }
}

From source file:utils.ReflectionService.java

public static JsonNode createJsonNode(Class clazz, int maxDeep) {

    if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) {
        return null;
    }// w ww .ja va 2  s  .c o m

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode objectNode = objectMapper.createObjectNode();

    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String key = field.getName();
        try {
            // is array or collection
            if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0];
                ArrayNode arrayNode = objectMapper.createArrayNode();
                arrayNode.add(createJsonNode(type, maxDeep - 1));
                objectNode.put(key, arrayNode);
            } else {
                Class<?> type = field.getType();
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                } else if (type.isEnum()) {
                    objectNode.put(key, Enum.class.getName());
                } else if (!type.getName().startsWith("java") && !key.startsWith("_")) {
                    objectNode.put(key, createJsonNode(type, maxDeep - 1));
                } else {
                    objectNode.put(key, type.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return objectNode;
}

From source file:org.LexGrid.LexBIG.caCore.dao.orm.LexEVSDAOImpl.java

protected static void initializeAll(List<Object> list) {
    for (Object obj : list) {
        Class resultClass = obj.getClass();
        while (resultClass != null) {
            Field[] fields = resultClass.getDeclaredFields();
            for (int f = 0; f < fields.length; f++) {
                fields[f].setAccessible(true);
                try {
                    if (!Hibernate.isInitialized(fields[f].get(obj))) {
                        Hibernate.initialize(fields[f].get(obj));
                    }// w ww  . ja  va2 s .co m
                } catch (Exception e) {
                    throw new HibernateException("Error fully initializing.", e);
                }
            }
            resultClass = resultClass.getSuperclass();
        }
    }
}

From source file:com.sugaronrest.restapicalls.ModuleInfo.java

public static Iterable<Field> getFieldsUpTo(Class<?> type, Class<?> exclusiveParent) {
    List<Field> currentClassFields = new ArrayList<>();
    currentClassFields.addAll(Arrays.asList(type.getDeclaredFields()));

    Class<?> parentClass = type.getSuperclass();
    if (parentClass != null && (exclusiveParent == null || !parentClass.equals(exclusiveParent))) {
        List<Field> parentClassFields = (List<Field>) getFieldsUpTo(parentClass, exclusiveParent);
        currentClassFields.addAll(parentClassFields);
    }//from   w  ww .j  a v  a2s.co  m

    return currentClassFields;
}

From source file:com.aw.support.reflection.MethodInvoker.java

public static List getAllAttributes(Object target) {
    logger.info("searching attributes " + target.getClass().getName());
    List attributes = new ArrayList();
    Class cls = target.getClass();
    Field[] fields = cls.getDeclaredFields();
    Field[] superFields = cls.getSuperclass().getDeclaredFields();
    attributes.addAll(procesarFields("", fields));
    attributes.addAll(procesarFields("", superFields));

    // analizamos si tiene domain..
    BeanWrapper beanWrapper = new BeanWrapperImpl(target);
    try {//from w  ww.  ja  va 2 s. co  m
        Class claz = beanWrapper.getPropertyType("domain");
        if (claz != null) {
            Field[] fieldsDomain = claz.getDeclaredFields();
            Field[] superFieldsDomain = claz.getSuperclass().getDeclaredFields();
            attributes.addAll(procesarFields("domain.", fieldsDomain));
            attributes.addAll(procesarFields("domain.", superFieldsDomain));
        }
    } catch (Exception e) {
        logger.error("No tiene attributo domain");
    }
    return attributes;
}

From source file:index.IncrementIndex.java

/**
* 
* @param path//from   w  ww .  j  av  a  2  s .com
* @param storeIdPath
* @param rs
* @return 
*/
public static boolean indexBuilding(String path, String storeIdPath, ResultSet rs, String classPath,
        String keyName) throws SQLException {
    try {
        Analyzer luceneAnalyzer = new StandardAnalyzer();
        // ??ID??  
        boolean isEmpty = true;
        try {
            File file = new File(storeIdPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileReader fr = new FileReader(storeIdPath);
            BufferedReader br = new BufferedReader(fr);
            if (br.readLine() != null) {
                isEmpty = false;
            }
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //isEmpty=false?  
        IndexWriter writer = new IndexWriter(path, luceneAnalyzer, isEmpty);
        String storeId = "";
        boolean indexFlag = false;
        // ?
        Class c2 = Class.forName(classPath);
        // 
        java.lang.reflect.Field[] fields = c2.getDeclaredFields();
        while (rs.next()) {
            // list?    
            Map map = new HashMap();
            // ????
            for (java.lang.reflect.Field field : fields) {
                //  
                if (keyName.equals(field.getName())) {
                    storeId = rs.getString(field.getName().toUpperCase());
                }
                // ???
                if (whetherExist(field.getName().toUpperCase(), rs)) {
                    map.put(field.getName(), rs.getString(field.getName().toUpperCase()));
                }
            }
            writer.addDocument(Document(map));
            indexFlag = true;
        }
        writer.optimize();
        writer.close();
        if (indexFlag) {
            // ?ID?  
            writeStoreId(storeIdPath, storeId);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("" + e.getClass() + "\n   ?:   " + e.getMessage());
        return false;
    } finally {
        if (null != rs) {
            rs.close();
        }
    }

}

From source file:bdi4jade.util.ReflectionUtils.java

/**
 * Sets plan body fields annotated with {@link bdi4jade.annotation.Belief}.
 * /* w w w  .j  ava  2  s  .  c o m*/
 * @param planBody
 *            the plan body to be setup with beliefs.
 */
public static void setupBeliefs(PlanBody planBody) {
    Capability capability = planBody.getPlan().getPlanLibrary().getCapability();
    Class<?> currentClass = planBody.getClass();
    while (PlanBody.class.isAssignableFrom(currentClass)) {
        for (Field field : currentClass.getDeclaredFields()) {
            boolean b = field.isAccessible();
            field.setAccessible(true);
            try {
                if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                    if (Belief.class.isAssignableFrom(field.getType())) {
                        bdi4jade.annotation.Belief beliefAnnotation = field
                                .getAnnotation(bdi4jade.annotation.Belief.class);
                        String beliefName = beliefAnnotation.name();
                        if (beliefName == null || "".equals(beliefName)) {
                            beliefName = field.getName();
                        }
                        Belief<?, ?> belief = capability.getBeliefBase().getBelief(beliefName);
                        field.set(planBody, belief);
                    } else {
                        throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                    }
                }
            } catch (Exception exc) {
                log.warn(exc);
            }
            field.setAccessible(b);
        }
        currentClass = currentClass.getSuperclass();
    }
}