Alternatives to needing class file during deserialization?

Hi,
I'm trying to find a way of deserializing an object without requiring its class file (eg, class A) to be present. In that case the JVM instance that's deserializing an instance of class A wouldn't need to worry about needing to access the class A from its classpath (file "A.class") or from any other source (such as a custom classloader loading class A's bytecodes over the network) in order to deserialize an instance of class A, except when the source is the serialization stream itself -- all data needed for serialization would be contained only within the serialization stream.
I believe this should be doable by first serializing an instance of class java.lang.Class that represents class A (since java.lang.Class instances are serializable), and then serializing the instance of class A, as explained below. This technique isn't working, and I'm wondering if anyone knows why, and if there are other known techniques for accomplishing the same objective.
I start out with these classes as a test that serialization is working:
The class whose instance I'm serializing/deserializing:
class A implements java.io.Serializable {
     public int x = 5;
}Serialization code:
import java.io.*;
class Serialize {
     public static void main(String[] args) throws Exception {
          FileOutputStream fos = new FileOutputStream("a.ser");
          ObjectOutput out = new ObjectOutputStream(fos);
          A aRef = new A();
          out.writeObject(aRef);
          out.flush();
          out.close();
}Deserialization code:
import java.io.*;
class Deserialize {
     public static void main(String[] args) throws Exception {
          FileInputStream fis = new FileInputStream("a.ser");
          ObjectInput in = new ObjectInputStream(fis);
          A aRef = (A)in.readObject();
          in.close();
          System.out.println(aRef.x); //expect 5
}Here's what I do:
(1) javac A.java Serialize.java Deserialize.java
(2) java Serialize
(3) java Deserialize
This works fine, and prints "5" as expected.
Now that I know that this base case works, I next try to serialize an instance of class java.lang.Class into the stream. This instance will represent class A, and can be obtained by specifying the literal "A.class" in the source code as shown below. Then I serialize an instance of class A as before. I'll then repeat step (1) and (2), erase the "A.class" file, and then do step 3. Here's the new code:
The class whose instance I'm serializing/deserializing (same as before):
class A implements java.io.Serializable {
     public int x = 5;
}Serialization code:
import java.io.*;
class Serialize {
     public static void main(String[] args) throws Exception {
          FileOutputStream fos = new FileOutputStream("a.ser");
          ObjectOutput out = new ObjectOutputStream(fos);
          Class clazz = A.class;
          out.writeObject(clazz);
          A aRef = new A();
          out.writeObject(aRef);
          out.flush();
          out.close();
}Deserialization code:
import java.io.*;
class Deserialize {
     public static void main(String[] args) throws Exception {
          FileInputStream fis = new FileInputStream("a.ser");
          ObjectInput in = new ObjectInputStream(fis);
          Class clazz = (Class)in.readObject(); //shouldn't this cause class A to be loaded?
          A aRef = (A)in.readObject();
          in.close();
          System.out.println(aRef.x); //expect "5"
          System.out.println(clazz); //expect "class A"
}And now the revised steps:
(1) javac A.java Serialize.java Deserialize.java
(2) java Serialize
*(3) Delete the "A.class" file because it shouldn't be needed since we're now serializing an instance of class Class that should fully represent class A.*
(4) java Deserialize
Bam... exception thrown at step 4:
Exception in thread "main" java.lang.ClassNotFoundException: A
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at java.io.ObjectInputStream.resolveClass(Unknown Source)
        at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
        at java.io.ObjectInputStream.readClassDesc(Unknown Source)
        at java.io.ObjectInputStream.readClass(Unknown Source)
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at Deserialize.main(Deserialize.java:6)Why is a ClassNotFoundException thrown? Class A is already loaded automatically after the instance of class Class is deserialized, isn't it? It's possible that an instance of class Class doesn't store method bytecodes -- I'm not sure about that. But even so, I purposefully did not include any methods in class A -- I just made the data member public (bad form, but this is just a test).
Any ideas why this isn't working, or a way(s) to accomplish the goal?
Thanks,
Will

serializing java.lang.Class instance does not really write the content of the class file in to the stream. It only write a class descriptor. At the read end it will try to locate the class file locally and validate the class file with the information in the descriptor.
You need to have mechanism to send the data of the class file itself in to the stream before sending the instance.
take a look at the annotateClass and resolveClass methods in ObjectOutputStream and ObjectInputStream

Similar Messages

  • Need Class file of Reset Password in Logon par??

    Hi,
    I'm working on Forgot Password functionality in Logon par... I want to send customized mail to user once he click on Submit button of the Forgot Password application.
    Can anybody help me to find that..Which class file is being called in Logon par once user enter e-mail id in the text box and click on Submit button..
    I need to change the logic in this class to meet my requirements.
    Thanks a lot!!!
    -Vikas

    hi,
    first step is to select right par file.
    name of par file is :com.sap.portal.support.logon.par
    upload this PAR file to NWDS.
    code for Login page is present in the JSP-umLogonPage.jsp
    path for JSP file is
    dist\PORTAL-INF\umLogonPage.jsp
    regards,
    jayesh talreja

  • How do i compile a class file to become an exe (application file)

    I know jbuilder and other 3 rd party software are able to to that. I just want to know whether jdk1.3 compiler able to do it...

    Hm ...
    if you think of a compiler producing an executable file, this means, the application is compiled, linked and bound at file-level - what about the features of loading and linking classes during runtime or the ability to replace class files during runtime and load/link it dynamically?- Guess, a compiler for java can compile static applications, which need no dynamic linking of classes, but is it also able to keep this functionality of java this way?- I don't think so (but I never tested one of these compilers).
    greetings Marsian

  • Class not found during deserialization of descriptor UserSession

    I am using JDeveloper 3.1.1.2 (build 767) to deploy an EJB to Oracle 8.1.6 and I get the following error message....
    Generating EJBHome and EJBObject on the server...
    Class not found during deserialization of descriptor UserSession
    *** Errors occurred while deploying the EJB to JServer ***
    *** Deployment completed ***
    I've tried
    a) to deploy all the classes in the project,
    b) create a new project step by step,
    c) use 'deployejb' and I still get the same error...
    Can anyone help? Thanks.

    Yep, JDeveloper auto generates the <>.ejb and it is a binary file.
    Seems a pretty specific error message....any help available from the JDev team??

  • Need a simple network accessibility for RMI class files.

    I am trying to get an RMI server working and need a way to make the class files network accessible. The link: http://java.sun.com/javase/technologies/core/basic/rmi/class-server.zip does seem to have the server anymore. Anyone know where to get a copy of it?
    Is there a way to do this with Jini?
    Can oc4j be used?

    I am trying to get an RMI server working and need a way to make the class files network accessible. The link: http://java.sun.com/javase/technologies/core/basic/rmi/class-server.zip does seem to have the server anymore. Anyone know where to get a copy of it?
    Not much point really. That class file server only served .class files, not even JARs.
    Is there a way to do this with Jini?No.
    Can oc4j be used?Not by itself.
    Anything that will serve HTTP requests will do. Such as an HTTP server. Such as the one built into the JDK for example.

  • Just upgraded to jdk1.4 from 1.2 do I need to recompile all my class files?

    Just upgraded to jdk1.4 from 1.2 do I need to recompile all my class files?
    They run fine, but is there any benefit of recompiling all my class files?

    Nope. AFAIK you would experience exactly zero benefits from just recompiling the code. All that would do is regenerate the bytecode within the .class file(s), and as far as I know, the class file specification did not change. I am not aware of any modifications to the bytecode generation process in the 1.4 release that constitute actual changes in what's generated (for example, generating more efficient or optimized bytecode).
    (any other respondents feel free to correct me on this, as I admittedly spend very little of my time down at the bytecode and classfile level)
    -dSn

  • How to invoke a .class file on a perticuler time during the day

    i need to invoke a .class file everyday on a perticuler time, please help me in this regard, kindly give me some details and an example code if possible.

    OS'es tend to thave their ways to accomplish this.
    See crontab on Unices and so on.

  • 2 seperate class files, need some help

    Hi,
    Um, incase you didn't notice, I'm new to java. The closest to Java that I've ever been was C#. But anyways:
    I have 2 class files. One of them is a main form, and the other one is a simple dialog form. Is there a way that I can make the main form show the dialog form say, by clicking a button? I know how to create a button and do something when the button is clicked, I just don't know how to make one form show another one without having the code for both forms in one file. By the way, I'm making it in Swing if that makes a difference. Also, code examples would help, thanks.

    Hi,
    Um, incase you didn't notice, I'm new to java.The way about every second posts starts in here. Thanks for pointing it out, I wouldn't have guessed. :p
    The
    closest to Java that I've ever been was C#. But
    anyways:
    I have 2 class files. One of them is a main form, and
    the other one is a simple dialog form.
    Is there a way
    that I can make the main form show the dialog form
    say, by clicking a button?Yes, of course.
    I know how to create a
    button and do something when the button is clicked, I
    just don't know how to make one form show another one
    without having the code for both forms in one file.Uhm. Just something similar to
    MyDialog d = new myDialog(theFrameToBeModalTo);
    d.show();?
    What does it have to do with files? Java doesn't care about files.
    By the way, I'm making it in Swing if that makes a
    difference. Also, code examples would help, thanks.All code examples you need are here:
    http://java.sun.com/docs/books/tutorial/

  • Need help with "class file contains wrong class"

    I have a dbUtil package as
    package dbUtil;
    public class dbConfig {
    public String getHost(String db) {
    This file called dbConfig.java has been compiled with -d option and rthe class files resides in dir <install_dir>/webapps/test/WEB-INF/classes/eb/dbUtil/
    I have a jsp file in <install_dir>/webapps/test/test.jsp which imports the dbUtil package
    <%@ page import="eb.dbUtil.dbConfig" %>
    and I am getting this error:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: -1 in the jsp file: null
    Generated servlet error:
    [javac] Compiling 1 source file
    /opt/hpws/tomcat/work/Standalone/localhost/test/test_jsp.java:12: cannot access eb.dbUtil.dbConfig
    bad class file: /opt/hpws/tomcat/webapps/test/WEB-INF/classes/eb/dbUtil/dbConfig.class
    class file contains wrong class: dbUtil.dbConfig
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    import eb.dbUtil.dbConfig;
    ^
    1 error
    Can anyone tell me what am I doing wrong? I am using tomcat 4.1
    Thanks!
    L.

    Given your java file, the fully qualified name of the class is dbUtil.dbConfig.
    What you are importing is eb.dbUtil.dbConfig
    These things are not the same.
    The root of the classpath for the webapp is the classes directory.
    So either
    1 - specify dbConfig.java to be in package eb.dbUtil
    2 - move the class file into web-inf/classes/dbUtil/dbConfig.class, and import dbUtil.dbConfig.
    Also, by convention, classnames should start with a capital letter ie dbUtil.DbConfig.
    Cheers,
    evnafets

  • Need help with a class file!

    How do you decompress or decompile a class file??? I just can't seem to get it...

    One program is called JAD...
    Also the jedit program has a plugin to decompile class files.
    http://www.jedit.org
    Uwe

  • Urgent help needed with class file platform transfer

    Hi,
    I am working at home on Java in the windows (2000) system. Now I have compiled a java source code which compiles fine. This is an applet and works fine.
    However, when I am uploading the files( class files generated and the html file) to the Sun Unix system, the applet does not work. My first question is: Does this class file generated in Windows system not transferable in the Unix system?
    At this point, I uploaded the java source file to the Unix system. The source file has been created in Textpad in the Windows environment. Now using telnet I used the javac command to compile the source file in Unix system. Now, I am seeing three errors which was not the case in the Windows environment? I have no idea why the same source code is working on one platform and producing error in another?
    Any help is highly appreciated. Thanks. Regards.

    What are the errors?

  • JavaCompiler outputs .class files in wrong folder

    I'm trying to compile some code using the Compiler API. The code belongs to package "compile", however, upon compiling the code, the class file ends up in the root directory rather than in the "compile" folder as I was expecting. The compiler seems to be ignoring the package info. What am I doing wrong here?
    package compile;
    import java.io.IOException;
    import java.net.URI;
    import java.util.Arrays;
    import javax.tools.*;
    import javax.tools.JavaCompiler.CompilationTask;
    public class CompilerTest {
         private static final String code =
              "package compile;\n" +
              "class TestClass {\n" +
              "     public static void main(String[] args) {\n" +
              "          System.out.println(\"Hello World!\");\n" +
              "     }\n" +
              "}\n";
         public static void main(String[] args) {
              JavaStringObject source = new JavaStringObject("compile.TestClass", code);
              Iterable<? extends JavaFileObject> sources = Arrays.asList( source );
              JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
              CompilationTask task = compiler.getTask(null, null, null, null, null, sources);
              System.out.println( task.call() );
         /** Java source from a String */
         private static class JavaStringObject extends SimpleJavaFileObject {
              private final String code;
              public JavaStringObject(String className, String content) {
                   super( URI.create("string:///"+className.replace('.','/')+Kind.SOURCE.extension), Kind.SOURCE );
                   code = content;
              public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                   return code;
    }Thanks

    How do we know it is wrong?
    You are not showing where you compile and run this from.
    Also you are making it more confusing than it needs to be because your test class and the data for the compilation have the same package - I'd put CompilerTest and TestClass into different packages just to remove the potential for confusion.
    You are not specifying a -d option to the compiler.
    You are not specifying what the working directory is and the classpath when you run your test.
    You are not telling us where the generated class file is placed.
    When you say root directory do you mean the file system root, or the working directory or what?
    With some more information we might be able to either reproduce your fault or alternatively explain to you why what you are observing is the expected behaviour.
    Bruce

  • Any way to reduce class file size?

    Somewhere during my travels on the net I remember seeing something about a utility that reduces the size of java class files, eg by optimizing. I think it is an IBM product. Anybody know about this?
    I am writing a midlet that needs to be less than 70K in size (JAR file), but currently its at about 100K -- any suggestions on how to reduce the size of the class files?
    Thx,
    Fred

    Yes, I think you are refering to JAX by IBM.
    I have just started using it a couple of days ago. It reduced my 130k application to 70k good tool.
    Here is the link :
    http://www.alphaworks.ibm.com/tech/JAX
    Look for verion 6.1 that on if free. The new version is very expensive $1000 :(.
    6.1 works well.

  • How to load a .class file dynamically?

    Hello World ;)
    Does anyone know, how I can create an object of a class, that was compiled during the runtime?
    The facts:
    - The user puts a grammar in. Saved to file. ANTLR generates Scanner and Parser (Java Code .java)
    - I compile these file, so XYScanner.class and XYParser.class are available.
    - Now I want to create an object of XYScanner (the classnames are not fixed, but I know the filename). I tried to call the constructor of XYScanner (using reflection) but nothing works and now I am really despaired!
    Isn't there any way to instantiate the class in a way like
    Class c = Class.forName("/home/mark/XYScanner");
    c scan = new c("input.txt");
    The normal call would be:
    XYLexer lex = new XYLexer(new ANTLRFileStream("input.txt"));The problem using reflection is now that the parameter is a ANTLRFileStream, not only an Integer, as in this example shown:
    Class cls = Class.forName("method2");
    Class partypes[] = new Class[2];
    partypes[0] = Integer.TYPE;
    partypes[1] = Integer.TYPE;
    Method meth = cls.getMethod("add", partypes);
    method2 methobj = new method2();
    Object arglist[] = new Object[2];
    arglist[0] = new Integer(37);
    arglist[1] = new Integer(47);
    Object retobj = meth.invoke(methobj, arglist);
    Integer retval = (Integer)retobj;
    System.out.println(retval.intValue());Has anyone an idea? Thanks for each comment in advance!!!

    Dump all of your class files into a directory.
    Use the File class to list all files and iterateover
    the files.NastyNot really, when you are dynamically creating code, I would expect the output to be centralized, not spread out all over the place.
    >
    Use a URLClassloader to load the URL that isobtained
    for each file with file.toURI().toURL()(file.toURL()
    is depricated in 1.6)Wrong, the URL you give it must be that of the
    directory, not the class file.No, I did this quite recently, you can give it a specific class file to load.
    >
    Load all of the classes in this directory, thatway
    any anonymous classes are loaded as well.Anonymous classes automatically loaded when the real
    one isIt can't load it if it doesn't know where the code is. Since you haven't used a URL classloader to load once class file at a time, you would never encounter this. But if you loaded a class file that had an anonymous classfile it needed, would it know where to look for it?
    >
    From this point you should be able to just get a
    class with Class.forName(name)No. Class.forName uses the classloader of the class
    it's called in, which will be the system classloader.
    It won't find classes loaded by a URLClassLoader.got me there.

  • Is it possible to refer class files by mapping network drive?

    Hi,
    Is it possible to refer class files from the server(By mapping network of client's server) and specify this in project setting. If yes, how?
    Right now I copied all class file needed, to 'myclasses' directory of jdevhome. this approach is working fine but the page is taking 20 to 30 minutes to refresh.
    What could be probable reason for taking this much time to refresh a page? what could be alternative for this?
    Will the mapping of drive and referring it will improve the performance?
    I am connected to server through VPN and using Window based JDeveloper.
    Regards,
    Adarsh

    Hi Adarsh,
    For the first part of your query, You can create a new Library in Project Settings to refer to the server classes.
    As for the performance issue, there could be many reasons. Do you really think class loading is the only reason for the same? You might want to check in the Log window as to which process is eating up your time before loading the page.
    ~Srinath.

Maybe you are looking for

  • Cisco CSC Web Filtering and Citrix\Ts users

    Hello we need to buy a cisco CSC module for cisco ASA, and we're using Citrix Presentation server and Terminal Server Users, is CSC capable of ahtentitcate transparent the users in citrix (x users are using same IP)?, the CSC uses ntlm for this?, tha

  • Filtering

    Hi, I have a Radiobutton for personnel planning and when this is pressed and plant value is given at selection screen: the following data extracted from the corresponding tables and displayed in output: "use PSJ logical database to get project inform

  • Gaussian blur brush?

    Is it possible to select the brush tool and have it work as a gaussian blur brush? I'd like to be able to brush in the blur if possible to small areas rather than use the lasso tool method. THANKS

  • BADI COM_PARTNER_BADI

    Hello experts    I am trying to implement the BADI COM_PARTNER_BADI for determining Sold-to Parties from different Partner functions in a preceding document. But I notice that if I implement this, it only works when the Contact Person, Employee Respo

  • Why did running image processor in CS6 lose all changes to CR files?

    I am a creative cloud subscriber. I made and saved changes to my Camera Raw files in CS6. On running image processor these changes have all been lost. Can you help?