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

/**
 * As {@link #getAllFields(Class)} but acts on a list of {@link Class}s and
 * uses only {@link Class#getDeclaredFields()}.
 *
 * @param classes The list of classes to reflect on
 * @return The complete list of fields/*from www.j  ava  2  s .co m*/
 */
private static Field[] getAllFields(List<Class<?>> classes) {
    Set<Field> fields = new HashSet<Field>();
    for (Class<?> clazz : classes) {
        fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
    }

    return fields.toArray(new Field[fields.size()]);
}

From source file:Main.java

static Map<String, Object> objectToMap(Object object) {
    Map<String, Object> map = new HashMap<>();

    Class cls = object.getClass();
    while (cls != null) {
        for (Field field : cls.getDeclaredFields()) {
            field.setAccessible(true);// w ww. ja v  a  2s.  com

            Object value = null;
            try {
                value = field.get(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            if (value != null)
                map.put(field.getName(), value);
        }

        cls = cls.getSuperclass();
    }

    return map;
}

From source file:Main.java

/**
 * Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform.
 *///from www  .j a va 2 s  . c o m
private static sun.misc.Unsafe getUnsafe() {
    sun.misc.Unsafe unsafe = null;
    try {
        unsafe = AccessController.doPrivileged(new PrivilegedExceptionAction<Unsafe>() {
            @Override
            public sun.misc.Unsafe run() throws Exception {
                Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;

                for (Field f : k.getDeclaredFields()) {
                    f.setAccessible(true);
                    Object x = f.get(null);
                    if (k.isInstance(x)) {
                        return k.cast(x);
                    }
                }
                // The sun.misc.Unsafe field does not exist.
                return null;
            }
        });
    } catch (Throwable e) {
        // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError
        // for Unsafe.
    }
    return unsafe;
}

From source file:Main.java

public static void doGetAllField(Class<?> type, List<Field> fields, boolean ignoreSuperClasses) {
    for (Field newField : type.getDeclaredFields()) {
        boolean found = false;
        for (Field oldField : fields) {
            if (oldField.getName().equals(newField.getName())) {
                found = true;//  w w w.  jav  a 2 s  . c  o m
                break;
            }
        }
        if (!found) {
            fields.add(newField);
        }
    }

    if (type.getSuperclass() != null && !ignoreSuperClasses) {
        doGetAllField(type.getSuperclass(), fields, ignoreSuperClasses);
    }
}

From source file:Main.java

public static String getFields(Class clazz, Object object) {
    try {//  ww w.  j av  a2s .c  o  m
        StringBuilder builder = new StringBuilder();
        Field[] fs = clazz.getDeclaredFields();
        for (Field f : fs) {
            f.setAccessible(true);
            builder.append(f.getName() + "=" + f.get(object) + "\r\n");
        }
        return builder.toString();
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static List<Field> getAllFieldsWithAnnotation(List<Field> fields, Class<?> type,
        Class<? extends Annotation> annotationType) {
    for (Field field : type.getDeclaredFields()) {
        if (annotationType == null || field.getAnnotation(annotationType) != null) {
            fields.add(field);/*from   w ww. ja v  a  2s  . c  o m*/
        }
    }

    if (type.getSuperclass() != null) {
        fields = getAllFieldsWithAnnotation(fields, type.getSuperclass(), annotationType);
    }

    return fields;
}

From source file:com.dianping.lion.util.BeanUtils.java

public static Field[] getDeclaredFields(Class<?> clazz) {
    Assert.notNull(clazz);//from  w  ww.  j  av a 2 s  .  c om
    Field[] fields = clazz.getDeclaredFields();
    for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
        fields = (Field[]) ArrayUtils.addAll(fields, superClass.getDeclaredFields());
    }
    return fields;
}

From source file:Main.java

/**
 * Copy fields from parent object to child object.
 *
 * @param parent parent object/* w w w  .j  av a  2s.  co  m*/
 * @param child child object
 * @param <T> child class
 * @return filled child object
 */
public static <T> T shallowCopy(Object parent, T child) {
    try {
        List<Field> fields = new ArrayList<>();
        Class clazz = parent.getClass();
        do {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        } while (!(clazz = clazz.getSuperclass()).equals(Object.class));

        for (Field field : fields) {
            field.setAccessible(true);
            field.set(child, field.get(parent));
        }

        return child;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * @param type//from   w  w w. jav  a2  s .  c  o m
 * @param fieldName
 * @return
 */
private static Field getField(Class<?> type, String fieldName) {
    Class<?> currentType = type;
    while (!currentType.equals(Object.class)) {
        for (Field field : currentType.getDeclaredFields()) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        currentType = currentType.getSuperclass();
    }
    return null;
}

From source file:Main.java

public static boolean creteEntity(Object entity, String fileName) {
    boolean flag = false;
    try {/*from  www. j a  va  2  s .c om*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(fileName);

        Class clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Node EntityElement = document.getElementsByTagName(clazz.getSimpleName() + "s").item(0);

        Element newEntity = document.createElement(clazz.getSimpleName());
        EntityElement.appendChild(newEntity);

        for (Field field : fields) {
            field.setAccessible(true);
            Element element = document.createElement(field.getName());
            element.appendChild(document.createTextNode(field.get(entity).toString()));
            newEntity.appendChild(element);
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(fileName));
        transformer.transform(domSource, streamResult);
        flag = true;
    } catch (ParserConfigurationException pce) {
        System.out.println(pce.getLocalizedMessage());
        pce.printStackTrace();
    } catch (TransformerException te) {
        System.out.println(te.getLocalizedMessage());
        te.printStackTrace();
    } catch (IOException ioe) {
        System.out.println(ioe.getLocalizedMessage());
        ioe.printStackTrace();
    } catch (SAXException sae) {
        System.out.println(sae.getLocalizedMessage());
        sae.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return flag;
}