List of usage examples for java.io ObjectStreamClass lookup
public static ObjectStreamClass lookup(Class<?> cl)
From source file:GetSerVersUID.java
public static void main(String[] av) throws Exception { // First we construct a Class object for the given class Class cl = Class.forName("Candidate"); // Then an ObjectStreamClass for the given class ObjectStreamClass ocl = ObjectStreamClass.lookup(cl); // And use the ObjectStreamClass to get the Class' // unique SerialVersionUID System.out.println("For class " + cl); System.out.println("static final long serialVersionUID = " + ocl.getSerialVersionUID() + "L;"); // must be long // And just for reference... System.out.println("(Must range from " + Long.MIN_VALUE + " to " + Long.MAX_VALUE + ".)"); }
From source file:Main.java
public static void main(String[] args) throws Exception { String s = "Hello World from java2s.com"; FileOutputStream out = new FileOutputStream("test.txt"); ObjectOutputStream oout = new ObjectOutputStream(out); // write something in the file oout.writeUTF(s);/* w w w . j av a 2 s.co m*/ oout.flush(); oout.close(); // create an ObjectInputStream for the file we created before Main ois = new Main(new FileInputStream("test.txt")); // read and print an object and cast it as string System.out.println((String) ois.readUTF()); // get the class for string and print the name ObjectStreamClass streamClass = ObjectStreamClass.lookup(Integer.class); System.out.println(ois.resolveClass(streamClass).getName()); ois.close(); }
From source file:ClassVersionInfo.java
public ClassVersionInfo(String name, ClassLoader loader) throws ClassNotFoundException { this.name = name; Class c = loader.loadClass(name); CodeSource cs = c.getProtectionDomain().getCodeSource(); if (cs != null) location = cs.getLocation();// w w w . j a v a 2s.c o m if (c.isInterface() == false) { ObjectStreamClass osc = ObjectStreamClass.lookup(c); if (osc != null) { serialVersion = osc.getSerialVersionUID(); try { c.getDeclaredField("serialVersionUID"); hasExplicitSerialVersionUID = true; } catch (NoSuchFieldException e) { hasExplicitSerialVersionUID = false; } } } }
From source file:info.debatty.jinu.CaseResult.java
/** * * @return//w ww. ja va2s . c o m */ public final long getCaseVersion() { return ObjectStreamClass.lookup(testcase.getClass()).getSerialVersionUID(); }
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()./* www .j ava2 s .com*/ * * @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 .ja va2s .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:edu.cmu.tetrad.util.TetradSerializableUtils.java
/** * Deserializes examplars stored in archives in getArchiveDirectory(). * * @throws RuntimeException if clazz cannot be serialized. This exception * has an informative message and wraps the * originally thrown exception as root cause. * @see #getArchiveDirectory()/*from ww w . j av a 2 s . c om*/ */ public void deserializeArchivedVersions() throws RuntimeException { System.out.println("Deserializing archived instances in " + getArchiveDirectory() + "."); File archive = new File(getArchiveDirectory()); if (!archive.exists() || !archive.isDirectory()) { return; } String[] listing = archive.list(); for (String archiveName : listing) { if (!(archiveName.endsWith(".zip"))) { continue; } try { File file = new File(getArchiveDirectory(), archiveName); ZipFile zipFile = new ZipFile(file); ZipEntry entry = zipFile.getEntry("class_fields.ser"); InputStream inputStream = zipFile.getInputStream(entry); ObjectInputStream objectIn = new ObjectInputStream(inputStream); Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject(); zipFile.close(); for (String className : classFields.keySet()) { // if (classFields.equals("HypotheticalGraph")) continue; List<String> fieldNames = classFields.get(className); Class<?> clazz = Class.forName(className); ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz); if (streamClass == null) { System.out.println(); } for (String fieldName : fieldNames) { assert streamClass != null; ObjectStreamField field = streamClass.getField(fieldName); if (field == null) { throw new RuntimeException("Field '" + fieldName + "' was dropped from class '" + className + "' as a serializable field! Please " + "put it back!!!" + "\nIt used to be in " + className + " in this archive: " + archiveName + "."); } } } } catch (ClassNotFoundException e) { throw new RuntimeException("Could not read class_fields.ser in archive + " + archiveName + " .", e); } catch (IOException e) { throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e); } System.out.println("...Deserializing instances in " + archiveName + "..."); ZipEntry zipEntry = null; try { File file = new File(getArchiveDirectory(), archiveName); FileInputStream in = new FileInputStream(file); ZipInputStream zipinputstream = new ZipInputStream(in); while ((zipEntry = zipinputstream.getNextEntry()) != null) { if (!zipEntry.getName().endsWith(".ser")) { continue; } ObjectInputStream objectIn = new ObjectInputStream(zipinputstream); objectIn.readObject(); zipinputstream.closeEntry(); } zipinputstream.close(); } catch (ClassNotFoundException e) { throw new RuntimeException( "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName + ". " + "Perhaps the class was renamed, moved to another package, or " + "removed. In any case, please put it back where it was.", e); } catch (IOException e) { throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e); } } System.out.println("Finished deserializing archived instances."); }
From source file:com.gs.collections.impl.test.Verify.java
public static void assertSerializedForm(long expectedSerialVersionUID, String expectedBase64Form, Object actualObject) {/*www . j a va2 s . c o m*/ try { Verify.assertInstanceOf(Serializable.class, actualObject); Assert.assertEquals("Serialization was broken.", expectedBase64Form, Verify.encodeObject(actualObject)); Object decodeToObject = Verify.decodeObject(expectedBase64Form); Assert.assertEquals("serialVersionUID's differ", expectedSerialVersionUID, ObjectStreamClass.lookup(decodeToObject.getClass()).getSerialVersionUID()); } catch (AssertionError e) { Verify.throwMangledException(e); } }
From source file:org.apache.ode.bpel.engine.migration.CorrelationKeySetMigration.java
private ExecutionQueueImpl readOldState(ProcessInstanceDAO instance, OProcess oprocess, ClassLoader cl, boolean changeKey) { if (instance.getExecutionState() == null) return null; try {//from w w w. j a va2 s . co m ExecutionQueueImpl soup = new ExecutionQueueImpl(cl); ObjectStreamClass osc; if (changeKey) { osc = ObjectStreamClass .lookup(Class.forName("org.apache.ode.bpel.engine.migration.OldCorrelationKey", true, cl)); ExecutionQueueImpl._classDescriptors.put("org.apache.ode.bpel.common.CorrelationKey", osc); } osc = ObjectStreamClass .lookup(Class.forName("org.apache.ode.bpel.engine.migration.OldSelector", true, cl)); ExecutionQueueImpl._classDescriptors.put("org.apache.ode.bpel.runtime.Selector", osc); osc = ObjectStreamClass.lookup(Class.forName("[Lorg.apache.ode.bpel.engine.migration.OldSelector;", true, getClass().getClassLoader())); ExecutionQueueImpl._classDescriptors.put("[Lorg.apache.ode.bpel.runtime.Selector;", osc); soup.setReplacementMap(new ReplacementMapImpl(oprocess)); ByteArrayInputStream iis = new ByteArrayInputStream(instance.getExecutionState()); soup.read(iis); return soup; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.openjpa.enhance.PCEnhancer.java
/** * Adds the code to properly handle PersistenceCapable serialization * to the bytecode. This includes creating and initializing the * static <code>serialVersionUID</code> constant if not already defined, * as well as creating a custom <code>writeObject</code> method if the * class is Serializable and does not define them. *///w w w .ja v a2s . c o m private void addSerializationCode() { if (externalizeDetached() || !Serializable.class.isAssignableFrom(_meta.getDescribedType())) return; if (getCreateSubclass()) { // ##### what should happen if a type is Externalizable? It looks // ##### like Externalizable classes will not be serialized as PCs // ##### based on this logic. if (!Externalizable.class.isAssignableFrom(_meta.getDescribedType())) addSubclassSerializationCode(); return; } // if not already present, add a serialVersionUID field; if the instance // is detachable and uses detached state without a declared field, // can't add a serial version UID because we'll be adding extra fields // to the enhanced version BCField field = _pc.getDeclaredField("serialVersionUID"); if (field == null) { Long uid = null; try { uid = ObjectStreamClass.lookup(_meta.getDescribedType()).getSerialVersionUID(); } catch (Throwable t) { // last-chance catch for bug #283 (which can happen // in a variety of ClassLoading environments) if (_log.isTraceEnabled()) _log.warn(_loc.get("enhance-uid-access", _meta), t); else _log.warn(_loc.get("enhance-uid-access", _meta)); } // if we couldn't access the serialVersionUID, we will have to // skip the override of that field and not be serialization // compatible with non-enhanced classes if (uid != null) { field = _pc.declareField("serialVersionUID", long.class); field.makePrivate(); field.setStatic(true); field.setFinal(true); Code code = getOrCreateClassInitCode(false); code.beforeFirst(); code.constant().setValue(uid.longValue()); code.putstatic().setField(field); code.calculateMaxStack(); } } // add write object method BCMethod write = _pc.getDeclaredMethod("writeObject", new Class[] { ObjectOutputStream.class }); boolean full = write == null; if (full) { // private void writeObject (ObjectOutputStream out) write = _pc.declareMethod("writeObject", void.class, new Class[] { ObjectOutputStream.class }); write.getExceptions(true).addException(IOException.class); write.makePrivate(); } modifyWriteObjectMethod(write, full); // and read object BCMethod read = _pc.getDeclaredMethod("readObject", new Class[] { ObjectInputStream.class }); full = read == null; if (full) { // private void readObject (ObjectInputStream in) read = _pc.declareMethod("readObject", void.class, new Class[] { ObjectInputStream.class }); read.getExceptions(true).addException(IOException.class); read.getExceptions(true).addException(ClassNotFoundException.class); read.makePrivate(); } modifyReadObjectMethod(read, full); }