Example usage for java.io ObjectStreamClass getFields

List of usage examples for java.io ObjectStreamClass getFields

Introduction

In this page you can find the example usage for java.io ObjectStreamClass getFields.

Prototype

public ObjectStreamField[] getFields() 

Source Link

Document

Return an array of the fields of this serializable class.

Usage

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//from  ww w  .jav  a2  s .  c o m
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance");
            Object object = method.invoke(null);

            File file = new File(current, clazz.getName() + ".ser");
            boolean created = file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        @SuppressWarnings("Convert2Diamond")
        List<String> fieldList = new ArrayList<>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//from w w w .  j  a v  a  2s .c o m
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance", new Class[0]);
            Object object = method.invoke(null, new Object[0]);

            File file = new File(current, clazz.getName() + ".ser");
            file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        List<String> fieldList = new ArrayList<String>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:org.openengsb.core.persistence.internal.SerializableChecker.java

private void checkFields(Object obj, ObjectStreamClass desc) {
    int numFields;
    try {/* w w w. j a  v a2s.co  m*/
        numFields = (Integer) getNumObjFieldsMethod.invoke(desc, (Object[]) null);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    if (numFields > 0) {
        int numPrimFields;
        ObjectStreamField[] fields = desc.getFields();
        Object[] objVals = new Object[numFields];
        numPrimFields = fields.length - objVals.length;
        try {
            getObjFieldValuesMethod.invoke(desc, obj, objVals);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < objVals.length; i++) {
            if (objVals[i] instanceof String || objVals[i] instanceof Number || objVals[i] instanceof Date
                    || objVals[i] instanceof Boolean || objVals[i] instanceof Class) {
                continue;
            }

            // Check for circular reference.
            if (checked.containsKey(objVals[i])) {
                continue;
            }

            ObjectStreamField fieldDesc = fields[numPrimFields + i];
            Field field;
            try {
                field = (Field) getFieldMethod.invoke(fieldDesc, (Object[]) null);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }

            field.getName();
            simpleName = field.getName();
            fieldDescription = field.toString();
            check(objVals[i]);
        }
    }
}