Serialization and reflection

I have a client/server application that talks to other instances of itself through ObjectStreams.
One instance of the application is host and another is client.
It is used to play multiplayer games.
Each game is contained in a jar file, from which the main-class is loaded in by the application at runtime with uRLClassLoader.loadClass("name of the main-class"). That main-class extends GameInterface.
The host tells the client which game it is running through a String.
The client then checks all the loaded GameInterfaces to see if it has the required game.
Once connnected, the server and client send Serializable objects to each other.
The problem is that some of those Serializable objects are classes from within a game's jar file (which are loaded in with reflection at runtime).
The host can get DiceSettings through the GameInterface of Dice for example. DiceSettings is in Dice's jar file.
But when the client receives DiceSettings in it's objectstream, it doesn't recognize it at the client:
java.lang.ClassNotFoundException: simplegamenet.games.dice.DiceSettings
1) How can I tell the ObjectInputStream that it also should use my URLClassCloader to create classes?
2) Which are the rules to be able to send an object through an objectStream?
Thanks for any and all help :)

Hi,
I worked myself on such an application. It works fine. Here is some code:
- for my class loader:
class JarClassLoader extends ClassLoader
private HashMap resMap=new HashMap(8000,0.9f);
JarClassLoader()
void addJar(byte[] jar)
try
JarInputStream jis=new JarInputStream(new ByteArrayInputStream(jar));
byte[] buffer=new byte[10240];
for(JarEntry je=jis.getNextJarEntry();je!=null;je=jis.getNextJarEntry())
String name=je.getName();
try
ArrayList data=new ArrayList();
int size=0;
for(int len=jis.read(buffer);len>0;len=jis.read(buffer))
byte[] real=new byte[len];
System.arraycopy(buffer,0,real,0,len);
data.add(real);
size+=len;
byte[] finalData=new byte[size];
int crt=0;
for(int f=0;f<data.size();f++)
byte[] chunk=(byte[])data.get(f);
System.arraycopy(chunk,0,finalData,crt,chunk.length);
crt+=chunk.length;
resMap.put(name,finalData);
catch(Exception e)
System.out.println(e);
jis.close();
catch(Throwable t)
t.printStackTrace(System.out);
public InputStream getResourceAsStream(String name)
byte[] bytes=(byte[])(resMap.get(name));
if(bytes==null)
return null;
return new ByteArrayInputStream(bytes);
public Class findClass(String name) throws ClassNotFoundException
String name1=name.replace('.','/').concat(".class");
byte[] b=(byte[])(resMap.get(name1));
if(b==null)
throw new ClassNotFoundException("Class:"+name+" not found");
Class c=defineClass(name,b,0,b.length);
return c;
- for the launcher:
ois=the ObjectInputStream
jcl=the JarClassLoader
byte[] jar=downloadFile("myjar.jar",ois);
String command=ois.readObject().toString();
jcl.addJar(jar);
runCommand(command,args);
private void runCommand(final String command,final String[] args)
try
Class c=Class.forName(command,true,jcl);
Method m=c.getMethod("main",new Class[] {args.getClass()});
m.invoke(null,new Object[] {args});
catch(Throwable t)
t.printStackTrace(System.out);
}

Similar Messages

  • MTS with batch management, serialization and Handling unit

    Hello All,
    I am testing a scenario for MTS with batch management, serialization and Handling unit for discrete manufacturing.
    Everything worked fine till I created the Handling unit for the finished product.
    The production order has a quantity of 3 EA.
    It has three serial numbers 1, 2 and 3. (serial numbers can be displayed from order->Header->serial numbers)
    I created one Handling unit for production order quantity of 3 EA.
    I tried to do a goods receipt for the production order using transaction COWBHUWE.
    I get the following error when I try to post the GR:
    Only 0 serial numbers entered instead of 3
    Message no. IO304
    Diagnosis
    There is a serial number obligation, so the number of serial numbers must equal the number of serial numbers in the material document.
    You can post the operation only if you entered the correct number of serial numbers previously.
    System Response
    Depending on the context in which the error arises, the system continues processing, or the required function cannot be performed.
    Procedure
    You have the following options, for example:
    Check that the serial numbers are entered fully.
    If necessary, display an error log.
    If necessary, contact your system administrator.
    What did I miss?
    How to fix this problem?
    Please help.
    Thanks in advance
    George

    I added the serialization procedure HUSL to the serial number profile and it fixed the problem.

  • [svn:bz-trunk] 22429: Adding the default fallback of serializer and deserializer classes to amf deserializer and amf serializer

    Revision: 22429
    Revision: 22429
    Author:   [email protected]
    Date:     2011-09-07 08:04:46 -0700 (Wed, 07 Sep 2011)
    Log Message:
    Adding the default fallback of serializer and deserializer classes to amf deserializer and amf serializer
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/SerializationContext.java

  • E52 Date Display does not update and reflect the c...

    Right from day 1 the display date of my E52 does not update and reflect correct the correct date. Got the phone replaced once still the same issue. Called the customer service and they say there is no such problem with E52. They asked me to go to the repair center...(isnt that ridiculous to ask a customer of a new phone to do so?). I went to the repair center with a hope that they will replace it for me but all in vain. They also gave me a ridiculous answer that Nokia does not have a replacement policy...and I was like so is it Nokia's policy to sell broken and faulty mobiles? I was utterly dejected. The electronic store where I bought also refuse to replace because they think there is a problem and no matter I get it changed it will recur. I still do not have a solution as all my ways of getting this problem resolved are exhausted. Anyone has a solution or came across this issue which can be solved without repairing?

    Ok let me state my problem. There is a date display and at midnight the date should automatically change to the next date. However that does not happen. The dealer makes the following changes Control Panel>Settings>General>Date and time> Automatic time update> On and this does not solve the problem. Then I get the mobile replaced and that too has the same problem. after going through all permutations and combinations the problem persists. To quote the email from the Contact center for Nokia in HK this was what was suggested
    Menu→Ctrl. panel→Settings→General→Date and time→Time zone→please select Hong Kong→Automatic time update→please select Off
    However, if the situation still occurred by following the above settings, please be advised to bring your Nokia E52 along with the valid sales invoice to one of our Hong Kong Nokia Care Centres for the handset checking since we do not have such arrangement of replacing a new phone to you.
    Please help!!!

  • Diff between Serialization and Synchronization

    Hi I am new to java.
    Pl. give me the difference between Serialization and Synchronization.
    Thankq
    Sridhar

    Don't you look at the timestamps of posts? They could
    have been typing at the same time.
    /KajPlease stop! I'll die laughing. LOL
    Re: Diff between Serialization and Synchronization
    Author: Annie.   Apr 11, 2005 10:30 AM (reply 1 of 4)  
    Re: Diff between Serialization and Synchronization
    Author: glrao   Apr 12, 2005 8:31 AM (reply 2 of 4) I really like your sense of humor.
    xH4x0r

  • Diff between Serialization and Synchonization

    Hi I am new to java.
    Pl. give me the difference between Serialization and Synchonization.
    Thankq
    Sridhar

    Pl. give me the difference between Serialization and
    Synchonization.Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. The Java Serialization API provides a standard mechanism for developers to handle object serialization.
    Synchronization is intended to make the code thread safe by setting locks on objects.
    They are totally different concepts. I fail to understand how you intend to compare them.

  • Singleton serialization and weblogic - help!

    hi everyone,
    I'm trying to serialize a singleton cache object we're using for our (intranet)
    website running on weblogic 6.1. I've made sure the singleton class
    implements serializable, and i've also put the following method in the
    singleton class (ChartCache.java):
    private Object readResolve()
    return theInstance; //which is of type ChartCache
    By the way I'm using jdk 1.3. I've trawled the web and can't find anything to help me yet...
    Basically I've written a jsp to get the current instance of the cache
    and serialize it to a file. When I invoke another jsp i want it to
    reinflate the object and place it back into the weblogic jvm so it can
    once again be accessed as a singleton by all classes in the webapp. At
    the moment its just not working - the cache object will eventually
    take over half an hour to create (huge database processing going on)
    so I want the option, if weblogic falls over, to reinstantiate the
    cache without having to rebuild it from scratch. The cache will only
    be refreshed once a day.
    I'll c&p my jsp code below...
    ======================= restoreCache.jsp
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.io.*" %>
    <%@ page import = "com.drkw.agencylending.website.chartcache.*" %>
    <%@ page import = "com.drkw.agencylending.log.Logger" %>
    <%
    ChartCache theCache = null;
    try
    String filename = "chartCache.dat";
    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream in = new ObjectInputStream(fis);
    theCache = (ChartCache)in.readObject();
    in.close();
    catch(Exception e)
    Logger.log(e);
    %>
    Resurrected chart cache from file.
    ======================= saveCache.jsp
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.io.*" %>
    <%@ page import = "com.drkw.agencylending.website.chartcache.*" %>
    <%@ page import = "com.drkw.agencylending.log.Logger" %>
    <%
    ChartCache theCache = ChartCache.getInstance();
    String fileName = "chartCache.dat";
    try
    FileOutputStream fos = new FileOutputStream(fileName);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(theCache);
    oos.flush();
    oos.close();
    catch(Exception e)
    Logger.log(e);
    %>
    Wrote cache object to file.
    ============================
    At the moment, a file is getting written but it seems suspiciously
    small (73 bytes!) for what is a very large object. When I try to load
    it up again, I get no errors but when I call ChartCache.getInstance()
    (my singleton) it recreates the cache rather than using the one I've
    reinflated. BTW I don't need to worry about server clustering/JNDI to
    ensure I have a truly singleton instance - there will only ever be one
    JVM to worry about.
    Any help greatly appreciated!

    solved the problem using another technique. Rather
    than serialize the entire singleton object, I just
    serialized the hashmap (the only bit I really care
    about). Then in the private constructor, the class
    checks a database flag to see whether the singleton
    was created today - if not, I refresh the cache,
    otherwise load in the serialized hashmap and set that
    as my class member. No complicated jndi/ejb registry
    needed to get around it..!singleton serialization is not recommended in ejb enviroment, it will cause problems. in what you are doing, it is far better to persist the data values in a database.
    just for the sake of writing a serializable sington: in addition to what you do in a regular object, you would first check to see if this obj has been serialized, if it is, deserialize it and return this one. you would have to write your own method to do serialization, making sure you have only one place to serialize it, and let the object know where the file is.

  • IE 11 Crashs with Java 8 and Reflections

    I have had a number of Dell PC's that are crashing when using Java and Reflections for the web 2014  I have tried a number of things. Removed old Java installs, reset IE, removed Java and re-installed. So far the only thing that helps is re-staging
    the PC with the same updates and the same version of Java. The Java version we are using is 8.25. I am currently testing the following; remove all Java versions. Install Java version 7.17 ( this is the version Reflections installs when you do not have Java
    installed). Anyone have any help?
    Thanks.
    Bill
    MCSE MCP CCNA

    Hi Bill,
    Thanks for your reply.
    Based on my knowledge, the issue is likely to be caused by the compatibiliy issue, so would you please use the tool autoruns to disable third-party services under IE and see if that helps:
    1. Download and install autoruns
    https://technet.microsoft.com/en-us/sysinternals/bb963902.aspx
    2. Disable services under IE
    If that didn't help, we may involve the java application vendor to check the issue together, for more information, please refer to:
    https://social.technet.microsoft.com/Forums/en-US/b3474068-8b3b-469d-b279-53182bbc2429/ie-11-java-compatible-issue?forum=w8itproappcompat
    Thanks for your time and please feel free to let me know if anything is unclear.
    Best Regards,
    Susie
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Using serialize and deserialize methods generated by clientgen

    I am trying to use the classes generated by the weblogic.webservice.clientgen tool
    from the weblogic 8.1 release. I would like to be able to make direct use of
    the serialize and
    deserialize methods in the "Codec" classes that correspond to the various request
    and
    response object classes. However, these methods require SerializationContext
    and
    deserializationContext objects as inputs. Are these context objects things I
    can construct,
    manufacture and/or access? Are there any coding examples for using these methods?
    Thanks.
    Michael

    Bruce,
    Thanks for the response. I have seen the documentation before. What that shows
    me is how
    to write customized Serialize and Deserialize methods. What I want to do is call
    the ones that
    clientgen has already created for me. I would love to have these called by the
    internals of the
    generated code as part of the handling of service calls. My problem is that the
    web site
    that I'm calling for these services uses SSL, and every attempt to use the clientgen-generated
    services results in the following exception being raised:
    javax.net.ssl.SSLKeyException: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable
    certificate was received.
    Since I am successful in making SOAP calls to this same site -- certificate aren't
    an issue
    for these SOAP calls -- I thought that what I should try is to make the service
    calls myself
    using SOAP, but to use the generated Serialize and Deserialize methods
    to create the request body and process the response body surrounding the SOAP
    call.
    However, what I'd really like to do
    is figure out the cause of the SSLKeyException, and to make the service calls
    the way weblogic
    intended them to be made. So if you have any suggestions about what might
    be causing the exception, I'd appreciate the help.
    BTW. In addition to being able to make SOAP calls myself, I've also had some success
    making
    web service calls using code generated by Apache AXIS's wsdl2java tool and JWSDP's
    wscompile
    tool; however, neither of these wsdl processors are replacements for clientgen
    because they
    both have problems dealing with the complex structures described by wsdl files
    for the web
    services I'm trying to use.
    Bruce Stephens <[email protected]> wrote:
    Hi Michael,
    The De/SerializationContext are internal/private objects. The example
    in the doc (you have probably already seen) is a good starting point:
    http://e-docs.bea.com/wls/docs81/webserv/customdata.html#1052981
    Regards,
    Bruce
    BTW, Have you considered using XMLBeans?
    http://dev2dev.bea.com/technologies/xmlbeans/index.jsp
    Michael Horton wrote:
    I am trying to use the classes generated by the weblogic.webservice.clientgentool
    from the weblogic 8.1 release. I would like to be able to make directuse of
    the serialize and
    deserialize methods in the "Codec" classes that correspond to the variousrequest
    and
    response object classes. However, these methods require SerializationContext
    and
    deserializationContext objects as inputs. Are these context objectsthings I
    can construct,
    manufacture and/or access? Are there any coding examples for usingthese methods?
    Thanks.
    Michael

  • Regarding Serializable and subclasses.

    I have a an abstract parent class called 'Information'
    which implements Serializable and which has an abstract
    method called init().
    There are 2 subclasses that extend the parent class Information
    called SInformation_1 and SInformation_2 and implement the method init().
    Now as the parent class is Serialized,will the concrete subclasses
    also be Serializable?

    How long does it take to write a demo?
    import java.io.*;
    abstract class Base implements Serializable {
        public abstract void init();
    class D1 extends Base {
        public void init() {}
    class D2 extends Base {
        public void init() {}
    public class SerializableExample {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            Base obj1 = new D1();
            Base obj2 = new D2();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(baos);
            out.writeObject(obj1);
            out.writeObject(obj2);
            out.flush();
            out.close();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream in = new ObjectInputStream(bais);
            D1 d1 = (D1) in.readObject();
            D2 d2 = (D2) in.readObject();
    }

  • Serialize and Deserialze

    Hi everyone:
    I just want to know, say if you serialize an Object, obviously, the object will be stored in memory. But let us say if you deserialize it later on,
    will the object be clean by the Garbage Collector?

    Your question suggests you might misunderstand the terms serialize and deserialize. You serialize an object to send it to another computer or store it out of memory, for example in a file. The serialized object can then be deserialized back into an in-memory object. Did you already know that, or does that help clear it up?

  • Serialize and Deserialize

    Serialize and Deserialize with Oracle 9 and Oracle 10
    We have developed a client/server application. Client is a Java application and Server is written in C-Language; link between Java and C is RPC/JRPC.
    We have to serialize and then deserialize a stream in a clob field in Oracle DB. When we deserialize with Oracle 9 we have no problem; now, after a migration to Oracle 10G, the deserialize failed at client level.
    If we test in test environment (Oracle 9) with the same client and the same server we have no problem. The only difference between two enviroenment is only the version of Oracle (9 is OK - 10G is KO).
    We use the OCI api.
    The error message at client level is:
    java.io.InvalidClassException: rpc.wDichiarazione; local class incompatible: stream classdesc serialVersionUID = 2960125282182152041, local class serialVersionUID = 2960125281578161001
    Thanks of all
    Marco

    You've changed a class definition. It has nothing to do with the Oracle version. Recompile that class with
    private static long serialVersionUID = 2960125282182152041L;If you then get another exception, you need to evaluate the changes you've made to the class in the light of what it says about Versioning in the Serialization specification.

  • Difference between serialization and externalization

    Can any body explain me the difference between serialization and externalization
    with some example.

    Have you tried google?
    Serializable indicates that the object can be serialized by the default serializer, Externalizable means that the object itself will handle the serialization of the object.
    /Kaj

  • Serialization and Class Integration

    I have a class that I want to serialize in order to save it to a file. In terms of OO design what is the best way to go about integrating serialization into my classes?
    I was going to have two static methods that would read/write an object of the class from/to a stream, where both the stream and object are paramters to the method. Would it make sense to implement it this way or would it be considered messy?
    Thanks!

    All you have to do is add implements java.io.Serializable to the class definition and make sure that any non-static non-transient data members are also serializable (and so on recursively until closure).

  • Serialization and circular dependancies

    I am hoping to save some objects using serialization. However, I am worried about some circular dependacies.
    I have a list of authors and books. Each book is associated with an author. And each other has a list of books. Therefore there is a circular depedancy in that in each author is a reference to a book which has a reference to the author.
    Does std serialization take care of this or does it cause a problem?
    Thanks.

    I am hoping to save some objects using serialization.
    However, I am worried about some circular
    dependacies.
    I have a list of authors and books. Each book is
    associated with an author. And each other has a list
    of books. Therefore there is a circular depedancy in
    that in each author is a reference to a book which
    has a reference to the author.
    Does std serialization take care of this or does it
    cause a problem?What happened when you wrote a little program to test this?
    Did it create an infinitely large file? Were you able to serialize and deserialize successfully?

Maybe you are looking for