Bean, Serialization Question

Who can give me a good explanation of JavaBean. Or a good URL with examples.
What are the advatages of java beans, how ca I write one.
And what has it to do with Serialization.
Serialization where is it used? Examples.

There's nothing special about a JavaBean. In broad terms a JavaBean is simply a Java class that has been written using a particular style.
The most notable points are:
1) default constructor - ie, a constructor with no arguments
2) property accessors - eg, public String getName(), public void setName(String name), public boolean isEnabled()
The advantage is that you don't need to know about a JavaBean to use it - the methods indicate the various properties available and their data type. So Java can use Reflection to examine the bean and use it appropriately. In other words, you can find out and use the methods an Object has without knowing about its class in advance simply by examining their names.
A good example would be a visual component (like a button). By following the JavaBean conventions you end up with a class that can be distributed to other people and they can just plug it into their applications. Think of how a visual GUI editor gives you a property window for a component - this is simply exposing the information it derives by looking at the bean's method signatures.
There are other things that add extra value to JavaBeans like bean info classes and editor components but that's usually just confusing until you understand beans and their power.
Have a look at http://java.sun.com/products/javabeans (I think)
Serialisation is a somewhat different matter. This basically involves "saving an object". You can get a single instance of a class to be written to (eg) the filesystem and then load it again later. Obviously you can write your own methods for saving an object's state but serialisation is automatic and standard allowing it to be employed by other applications without knowledge of the objects that they're dealing with. Again, as with something like JavaBeans it enables you to represent the state without knowing about how the bean works. For example, a distributed application might serialise an object to transmit it between client and server. Note that serialisation does not require that the class being serialised follows the JavaBeans conventions, though - it's kind of a Java no-brainer if you like.
It would take a long time to explain the full benefits of JavaBeans and serialisation, however.
Hope this helps.

Similar Messages

  • EJB: Stateless Session Bean create() Question.

    Lets say I have a stateless session bean that fetches data from my database. The point of the bean is to just do large SQL searches and funnel data back to the client. The prolem I have is that I am somehow fighting memory leaks. Despite having checked the code a number of times, the memory usage on my appserver continues to climb no matter what I do. I have theorized that the problem might be in the way Im using ma DataFetchBean (DFB).
    When I start the client, he obtains a user session. This is a stateful session bean that he uses for almost all communication with the server. Then I call "getDataFetchBean" in the user session which calls DataFetchBeanHome.create(). Then the client holds onto the returned reference, using it for the live of his connection. As he disconnects, he calls remove on the bean.
    Question is this:
    1) Is it better for me to call create() prior to each call to the stateless session bean ?
    2) Do you have any theories on why im loosing memory with this setup?
    TIA
    -- Rob

    1. But I thought you were using a 'stateful session bean'?
    2. For stateless session beans, there is no direct link between a remote reference and an instance of the bean. It is safe to hang on to the remote reference as long as you would like, of course it may go stale if the server dies. You will also find that the create() method does not actually contact the server, so doing it each usage costs very little. So, either way you should be fine.
    3. As for memory leaks, make sure that you are closing all statements, result sets, etc. promptly. These are commonly the problem. Also, use hprof or some other profile tool to determine what types of data you are allocating and (with better tools) what types of data you may be holding on to references to.
    Chuck

  • Stateless Session Bean + EJB Question + Jboss

    Hello,
    If I have a stateless session bean on a linux machine and it works locally what do i need to do to access a method in the session bean from a remote windows machine.
    I would like to be able to execute my client jar file on a windows machine and have it access the jboss server on the linux machine. what do i need to do?
    i have the session bean working locally on both windows and linux machine. do i need to to have a JSP/Servlet to access the session bean? can the session bean not be accessed directly? what should my classpath look like? do I need to include extra jar files in my client jar file.?
    Thanks,
    Joyce

    Thanks guys for the help but I am still a little lost.
    My Client windows machine has the client jar file and all the other jar files. This is my client class
    package helloworld.client;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import java.util.Hashtable;
    import java.util.Properties;
    import helloworld.interfaces.HelloWorldHome;
    import helloworld.interfaces.HelloWorld;
    public class HelloClient
         public static void main(String[] args)
              Hashtable prop = new Hashtable();
              prop.put ("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
              prop.put ("java.naming.provider.url","jnp://172.16.220.160:1099");
              prop.put ("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
              try
                   Context ctx = new InitialContext(prop);
                   Object obj = ctx.lookup("ejb/helloworld/HelloWorld");
                   System.out.println(obj);
                   HelloWorldHome home = (HelloWorldHome)javax.rmi.PortableRemoteObject.narrow(obj, HelloWorldHome.class);
                   HelloWorld helloWorld = home.create();
                   String str = helloWorld.sayHelloEJB("JOYCE is COOL");
                   System.out.println(str);
                   helloWorld.remove();
              catch(Exception e)
                   e.printStackTrace();
    I get a NullPointer ie the home object is null. The IP address is the IP of the Linux machine that has Jboss running on.
    Questions are:
    1. Do I need to have Tomcat running on my client machine if I am to connect via HTTP? Does this alter my client code.?
    2. My JNDI lookup is what is causing the problem. Does my jboss.xml and my ejb-jar.jar look okay to you.
    jboss.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS//EN" "http://www.jboss.org/j2ee/dtd/jboss.dtd">
    <jboss>
    <enterprise-beans>
    <session>
    <ejb-name>helloworld/HelloWorld</ejb-name>
    <jndi-name>ejb/helloworld/HelloWorld</jndi-name>
    </session>
    </enterprise-beans>
    <resource-managers>
    </resource-managers>
    </jboss>
    ejb-jar.jar
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
    <ejb-jar >
    <description>No Description.</description>
    <display-name>Generated by XDoclet</display-name>
    <enterprise-beans>
    <!-- Session Beans -->
    <session >
    <description><![CDATA[No Description.]]></description>
    <ejb-name>helloworld/HelloWorld</ejb-name>
    <home>helloworld.interfaces.HelloWorldHome</home>
    <remote>helloworld.interfaces.HelloWorld</remote>
    <ejb-class>helloworld.session.HelloWorldBean</ejb-class>
    <session-type>Stateless</session-type>
    <transaction-type>Bean</transaction-type>
    </session>
    <!--
    To add session beans that you have deployment descriptor info for, add
    a file to your merge directory called session-beans.xml that contains
    the <session></session> markup for those beans.
    -->
    <!-- Entity Beans -->
    <!--
    To add entity beans that you have deployment descriptor info for, add
    a file to your merge directory called entity-beans.xml that contains
    the <entity></entity> markup for those beans.
    -->
    <!-- Message Driven Beans -->
    <!--
    To add message driven beans that you have deployment descriptor info for, add
    a file to your merge directory called message-driven-beans.xml that contains
    the <message-driven></message-driven> markup for those beans.
    -->
    </enterprise-beans>
    <!-- Relationships -->
    <!-- Assembly Descriptor -->
    <assembly-descriptor >
    <!-- finder permissions -->
    <!-- transactions -->
    <!-- finder transactions -->
    </assembly-descriptor>
    </ejb-jar>
    Do I need RMI ? Do I need to concern myself with CORBA? All Im looking for is a step by step to understanding what I need to configure? Is their some way I can debug?
    Thanks alot,
    Joyce

  • A tough one for EJB experts - Stateless session bean spec question

    I am busy learning more about EJBs and came across something confusing regarding the legal operations in the various container callback methods for stateless session beans.
    Specifically, the EJB spec states that in the ejbCreate() method, the SessionContext can be used to obtain a reference to the EJB Object. Now this makes perfect sense with stateful session beans, since the ejbCreate() method isn't called until a client is creating a bean and the container has linked that bean to the client's EJB Object. However, it is my understanding that when it comes to stateless session beans, the container creates the beans and adds them to the bean pool at its leisure. It is not until a business method is called by a client that a stateless bean is actually linked to an EJB object. So, how is it that a stateless bean could ever obtain a reference to an EJB Object from within ejbCreate(). Which EJB Object would it be linked to? This operation just doesn't appear to make sense in that context.
    Can anyone clarify this for me?

    Interesting question. I have such questions all the time! Here's a link to a similar discussion
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=70&t=000905
    Also, I tried this using Weblogic 8.1. Tried to access the EJBObject in ejbCreate before any business method was invoked. I did this by specifying a value for initial-beans-in-free-pool and found that the hash code for the EJBObject was the same for all the bean instances that were created on startup.
    I then invoked a business method and accessed the EJBObject in that method. Again the hash code for the object was the same as the one created on startup.
    Seemed to be that there is a 1:n relation between the EJBObject and bean instances.
    This may be container specific. The spec says the user should be able to invoke the getEJBObject() method in ejbCreate(), its upto the container to comply with it.

  • Indirection/Serialization question

    Hello,
    I have the web tier and session bean tier on two different jvms. I am sending over toplink pojos from the session bean to web tier. All my pojos have a writeObject(ObjectOutputStream out) method wherein the dependent objects are instantiated prior to serialization by invoking the size() method. This works fine on the web tier and parent objects as well as the dependents are instantiated properly with the appropriate values. However when we do the calls within the same EJB we get a message saying IndirectList not instiated. When I say the calls within the same EJB I mean say one method of one bean calls another method of the same EJB. If its a remote call the indirect list is instantiated but if its same the same bean we get the above message. Can somebody tell us what we are doing wrong ?
    Regards,
    Aswin.

    Seems odd. Are your SessionBeans using local or remote interfaces locally?
    It may be that your application server is somehow optimizing the local calls, what application server are you using?
    Could you include the exception and stack trace?

  • File Serializable question

    hi,
    i know i've seen plenty of posts asking how to transfer files, my question is why doesn't simplying sending a file object from the client to the server work, file just implement Serializable? is it because the contents don't travel with the object? i'm pretty sure the object will go across, via socket programming or rmi, but why not the contents, or will they?
    Thank you.

    Because the file object, to the best of my knowledge,
    does not hold the contents, it just contains
    information about the file, such as its path.Very true. I never thought about it in this depth before, but the [url http://java.sun.com/j2se/1.4.1/docs/api/java/io/File.html]API says:
    "An abstract representation of file and directory pathnames."
    That's all it is, a representation, not an actualy file.
    Cheers,
    Radish21

  • Serialization question: can't write an object

    this may be a simple question but I do need to find out what's wrong with the object I am trying to serialize:
    The method (included) I use to write object works fine for some simple objects but stops without giving any message for some complex objects. It stops at "out.writeObject(obj)". Is there any other exceptions need to be caught or something else. Thanks a lot.
    public void writeAnObject(Object obj) {
    ObjectOutputStream out = null;
    try {
    out = new ObjectOutputStream(new FileOutputStream("obj.saved"));
    out.writeObject(obj);
    out.close();
    } catch (FileNotFoundException e) {
    System.err.println("Caught FileNotFoundException");
    e.printStackTrace(System.err);
    } catch (IOException e) {
    System.err.println("Caught IOException ");
    e.printStackTrace(System.err);

    Ok, one last thing... don't know if it will make any differance but why not?! This is a class that I used successfully in several projects when serializising Collections to file:
    * @author Andrew
    * @version 1.0 (2000-11-24)
    public class PersistentStorage {
         // The objectoutputstream
         private ObjectOutputStream out;
         // The objectinputstream
         private ObjectInputStream in;
          * This method saves a collection persistent to specified file.
          * @param obj          The collection we want to save.
         public void saveCollection(Collection obj, String fileName)
              throws FileNotFoundException, IOException {
              // Create a objectoutputstream
              out = new ObjectOutputStream(new FileOutputStream(fileName));
              // Write the collection object to file
              out.writeObject(obj);
              // Close the objectoutputstream
              out.close();
          * This method read a collection object from specified file.
          * @return collection          The collection we have read.
         public Collection readCollection(String fileName)
              throws FileNotFoundException, IOException, ClassNotFoundException {
              // Create a objectinputstream
              in = new ObjectInputStream(new FileInputStream(fileName));
              // Asign the read object to a Collection "container"
              Collection collection = (Collection) in.readObject();
              // Close the objectinputstream
              in.close();
              return collection;
    }The differens is that I don't catch any exceptions in those method writing and reading objects. Only throw exceptions.
    Try it out and see if it helps... (last shot) ;)
    /Andrew

  • Java Bean Serialization bugs (2 of them)

    I have an EJB Primary Key with one public field - and I have hit 2 bugs trying to
    serialize it to XML. I am currently running Weblogic 7.0.0.1 - the version that shipped
    with Weblogic Platform last friday. I didnt have this problem with Weblogic 7.0 GA.
    The problems are:
    Bug 1) I have public JavaBean get/set methods for the field (its a string). The servicegen
    ANT task throws an error because the field is both a property AND a public field
    (though, there is no reason to do this according to the JAX-RPC spec)
    The error I get is:
    weblogic.xml.schema.binding.BindingException: Error: bean property and public field
    found with the same name: starId
    Bug 2) If I remove the get/set methods and regenerate (using servicegen again), it
    fails at runtime because the generated code is looking for get/set methods (ie, it
    is not accessing the public field directly).
    The error I get is:
    java.lang.NoSuchMethodError
    at com.bnpparibas.fi.gfit.services.instrument.bond.persistance.BondPKCodec.typedInvokeGetter(BondPKCodec.java:87)
    at com.bnpparibas.fi.gfit.services.instrument.bond.persistance.BondPKCodec.invokeGetter(BondPKCodec.java:56)
    at weblogic.xml.schema.binding.BeanCodecBase.gatherContents(BeanCodecBase.java:295)
    at weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase.java:253)
    at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.java:195)
    at weblogic.xml.schema.binding.SoapArrayCodecBase.serializeOneDimArray(SoapArrayCodecBase.java:605)
    Is this a known issue with the Weblogic Platform?
    Do you know where I can find the release notes for weblogic platform?
    Regards,
    Nick

    Yes, i am able to reproduce both. I am not sure whether (1) is a bug though.
    If the field is public and the class got get/set methods, it is not clear
    whether
    to access the value from the public field or by using the get/set method.
    Get/set methods may have side effects and user may not see the expected
    behavior. Anyway I will leave it to Scott to make the call.
    regards,
    -manoj
    "Nick Minutello" <[email protected]> wrote
    in message news:[email protected]...
    >
    >
    Actually, did you manage to reproduce both bugs?
    -Nick
    "manoj cheenath" <[email protected]> wrote:
    I am able to reproduce the public field deser problem on 7.0.0.1. I have
    used public fields before and it used to work. So this may be a
    regression
    on the 7.0.0.1 branch. CR081154 is filed on this issue and we should be
    able to send you a patch as soon as it get fixed.
    regards,
    -manoj
    "Nick Minutello" <[email protected]>
    wrote
    in message news:[email protected]...
    I have an EJB Primary Key with one public field - and I have hit 2 bugstrying to
    serialize it to XML. I am currently running Weblogic 7.0.0.1 - the
    version
    that shipped
    with Weblogic Platform last friday. I didnt have this problem withWeblogic 7.0 GA.
    The problems are:
    Bug 1) I have public JavaBean get/set methods for the field (its astring). The servicegen
    ANT task throws an error because the field is both a property AND a
    public
    field
    (though, there is no reason to do this according to the JAX-RPC spec)
    The error I get is:
    weblogic.xml.schema.binding.BindingException: Error: bean property andpublic field
    found with the same name: starId
    Bug 2) If I remove the get/set methods and regenerate (using servicegenagain), it
    fails at runtime because the generated code is looking for get/set
    methods
    (ie, it
    is not accessing the public field directly).
    The error I get is:
    java.lang.NoSuchMethodError
    at
    com.bnpparibas.fi.gfit.services.instrument.bond.persistance.BondPKCodec.type
    dInvokeGetter(BondPKCodec.java:87)
    at
    com.bnpparibas.fi.gfit.services.instrument.bond.persistance.BondPKCodec.invo
    keGetter(BondPKCodec.java:56)
    at
    weblogic.xml.schema.binding.BeanCodecBase.gatherContents(BeanCodecBase.java:
    295)
    at
    weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase.java:253)
    at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.java:195)
    atweblogic.xml.schema.binding.SoapArrayCodecBase.serializeOneDimArray(SoapArra
    yCodecBase.java:605)
    Is this a known issue with the Weblogic Platform?
    Do you know where I can find the release notes for weblogic platform?
    Regards,
    Nick

  • Need Help!! Problem with Bean Serializer in SOAP

    Hi.
    I have a webservice develope in Jdeveloper 9.0.3. The webservice is deploy in a 9ias 9.0.3. When a invoke a method with a complex type parameter i get this error:
    [SOAPException: faultCode=SOAP-ENV:Client; msg=No Deserializer found to deserialize a &apos;http://xml.apache.org/xml-soap:datPerWS_Tdatper&apos; using encoding style &apos;http://schemas.xmlsoap.org/soap/encoding/&apos;. [java.lang.IllegalArgumentException]]
    Please.SomeBody knows like resolve this problem?
    Thanks.

    Could you post your code, particularly the bean that you are passing? This code sample here gives some of the key rules including having an implementation of java.io.Serializable and setters/getters for each item:
    http://otn.oracle.com/tech/webservices/htdocs/samples/customtype/content.html
    Mike.

  • Bean confusion - questions - beginner

    jsp A
    <jsp:useBean id="searchHeaders" scope="session" class="database.Tool"/>
    <p><c:out value="${searchHeaders.searchHeaderMap}"/> // This shows my bean info
    <p><a href="/<c:out value="${param.newID}"/>/searchTooling.jsp?newID=<c:out value="${param.newID}"/>">Tool Lookup </a>Quick Background
    When a user clicks on the above link they are taken to a form with two input fields where they can search by an asset number or a serial number. However, depending on what site they are on - the wording might be different - asset number might be called quality number or something else.
    <jsp:useBean id="searchHeaders" scope="session" class="database.Tool"/> 
    <c:forEach var="i" items="${searchHeaders.searchHeaderMap}" varStatus="status">
              <c:forEach var="h" items="${i.key}" varStatus="status">
                  <c:choose>
                  <c:when test='${(i.key) <= "2"}'>
                      <c:forEach var="d" items="${i.value}" varStatus="status">
                      <td><c:out value="${d}"/><INPUT TYPE='text' NAME='<c:out value="${d}"/>' SIZE='30'></td> 
                   </c:forEach>     
                  </c:when>
                  </c:choose>
              </c:forEach>
              </c:forEach>My problem is that jsp A has the bean information showing but once I click on a link the bean information doesnt show until I submit the form on jsp B( which forwards back to jsp B through servlet). I thought that once I called the bean and put it in a session scope I would be able to use it/call it until I expired the session...
    How can I share a bean between two jsp's without using a form?

    First of all - sorry if my terms dont make sense - still new and learning. I dont understand what you are asking me..
    Here is the servlet that is calling/creating the bean
    public class tooling_index extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            DataFactory dbf = DataFactory.getDataFactory(DataFactory.sybase);
            ToolSearchInformation searchInfo = dbf.getToolSearchInformation();
            Tool searchHeaders = searchInfo.findSearchTableHeaders(newID);
            request.setAttribute("searchHeaders", searchHeaders);
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp?newID="+ newID);
            dispatcher.forward(request, response);
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            doGet(request, response);
    }This forwards to my jsp A. Is this what you are asking ?

  • Java.io in J2ee stateless session bean, general questions about debugging

    Doing conventional Java IO (with java.io functions and classes such as
    PrintWriter and println) in a Enterprise bean has been discussed before
    in this and other forum. We know that the EJB specification says not to do it.
    (For example the EJB 2.0 spec, 24.1.2) says that an enterprise
    bean must not use the java.io package to attempt to access files and
    directories int he file system."
    The discussion in various forums including this one is that
    a) using java.io in a bean would impact portability, ability to
    move the bean for load balancing
    b) However, this is not always an an issue and it may be reasonable
    to use these functions anyway. e. g. see the response by "maozhoulu"
    on Jun 21, 2002.
    I tried it in Sun Application Server Nine in my stateless Session Bean:
    package RS;
    import RS.CourseHome;
    import RS.CoursePK;
    import java.rmi.RemoteException;
    import javax.naming.InitialContext;
    import javax.naming.Context;
    import javax.rmi.PortableRemoteObject;
    import javax.ejb.EJBException;
    import java.io.*;
    public class AddCourseBean implements javax.ejb.SessionBean {
       public void ejbCreate(){};
       public void CreateCourse (int CourseNumber, String CourseName) {
        try {
         System.out.println("in Create Course");
         PrintWriter F = null;
         try {
          F = new PrintWriter (new FileOutputStream("/tmp/v/af"));
         catch (java.io.FileNotFoundException fe){}
         F.println ("here zero");F.flush();
         InitialContext jndiContext = new InitialContext();
         F.println ("here one");F.flush();
         Object o = jndiContext.lookup("ejb/X");
             ...I got a Null pointer exception on the line:
    "F.println("here zero"); Is there anyway one can do simple debugging with print lines in one's beans?
    Or is there something obviousthat I am overlooking? (I saw mention of doing
    debugging with System.out.println but to where would the bean write?)
    I tried using the Jakarta Commons Logging, but I got a
    java.lang.NoClassDefFoundError on org/apache/commons/logging/LogFactory
    Which logging system does one use in GlassFish, hopefully one with minimal
    configuration? I want to do some debugging, not set up logging for a full
    enterprise system.
    Thanks for your insight and advice.
    Dr. Laurence Leff, Associate Professor of Computer Science WIU ST447 61455
    Pager 309 367 0787, Fax 309 298 2302

    My apology for posting this message twice. I looked for it before and
    did not see it. I thought I forget to click the "Post message" button.
    Also, I did resolve one problem. System.out.println does go to
    the log file, which in my case turned out to be:
    /opt/j2ee/SUNWappserver/domains/domain1/logs/server.log
    (Obvously, the first part would vary based upon where you installed your
    Application Server Nine.)
    However, it would be nice if there was some way to use FILE I/O inside of
    beans. I am teaching some J2EE in the graduate software engineering course,
    and I believe this would be pedagogically sound even if other techniques
    would be appropriate for a production environment.
    Thanks for your patience with this problem and my duplicate post.

  • Creative suite Standard CS 5.5 Serialization question

    Hi Everyone,
    I've got the following license :
    Adobe Design Std CS5.5 5.5 MLP Upgrade License IE FROM CS4 (65122148)
    Is it possible to serialize single application with the Adobe Provisioning Toolkit Enterprise Edition?
    Because when i try to serialize Photoshop CS5.5 i get an error code 3
    adobe_prtk.exe --tool=ReplaceSN --serialize=Photoshop-CS5.5-Win-GM --serial=xxxx
    When i use :
    adobe_prtk.exe --tool=ReplaceSN --serialize=DesignSuiteStandard-CS5.5-Win-GM --serial=xxxx
    it does work.
    Tia. Grz, Gianni

    if that's a mac warning about an unrecognized publisher, OS X Mountain Lion: The app is from an unidentified developer

  • Simple serialization question with objects

    Hi, I'm really new to the whole concept of serialization and what I want to do is create a blackjack game that can have up to 4 people playing, connected to a server that will act as the dealer. I need to be able to serialize some objects from the players to the server and have the server make some changes then send the objects back.
    However every example I've run across dealing with something of this nature involves writing to a file so I'm not sure what the code to do this would look like.
    My best guess would be ObjectInputStream and ObjectOutputStream but I don't understand how I can tell these streams that I just want to send the serialized object back and forth.
    If anyone could explain to me a bit better how these streams work, or show me roughly what the code might look like, I would really appreciate it.

    It doesn't matter whether you write to a file or a socket or a byte array or whatever. That stuff is what's under the ObjectOutputStream. When you create the OOS, you wrap it around some other stream (e.g. a FileOutputStream in the examples you're talking about I guess). To send something to a server, you'd instead just wrap it around the OutputStream of a Socket that's talking to that server. Everything else is the same.
    Whether you use raw sockets or some other means is up to you, but that's completely separate from the serialize/deserialize process.
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Object Serialization Question.

    Hello, I'm working on a MUD client and I have a DataHolder class to store settings. I'm having problems getting the serialization process to work properly, could someone please give me an example of how to serialize this class and then restore it again? I would like to save the class as "prefs.ser" Here is an example class to use:
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    public class DataHolder
         public Color foreground = Color.black;
         public Color background = Color.yellow;
    // i dont want to save the socket info since it will change many times during actual operation
    // also i know you have to catch the exception from the socket creation : )
         public transient Socket socket = new Socket("lordsoftherealm.org", 1234);
         public DataHolder()
         public setColors(Color foreground, Color background)
              // set background and foreground colors
              // the actual class include methods to retrieve colors, sockets, and other relevent data
              this.foreground = foreground;
              this.background = background;
         public Socket getSocket()
              return socket;
    }Thank you for your time in helping me,
    Joeyford1

    Try this,
    I am using this method to serializeand deserialize my objects ..
    import java.util.Date;
    import java.math.BigDecimal;
    import java.io.*;
    * This object compliments MyObjectTranslator and provides a method to translate
    * any object into a type the database engine can process.
    public class MyObjectTranslator {
    public static Object translate(Object ob) {
    if (ob == null ||
    ob instanceof NullObject ||
    ob instanceof String ||
    ob instanceof BigDecimal ||
    ob instanceof Date ||
    ob instanceof ByteLongObject ||
    ob instanceof Boolean) {
    return ob;
    else if (ob instanceof Serializable) {
    return serialize(ob);
    else {
    // System.out.println("Ob is: (" + ob.getClass() + ") " + ob);
    System.out.println("Unable to translate object. " +
    "It is not a primitive type or serializable.");
    * Serializes the Java object to a ByteLongObject.
    public static ByteLongObject serialize(Object ob) {
    try {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream ob_out = new ObjectOutputStream(bout);
    ob_out.writeObject(ob);
    ob_out.close();
    return new ByteLongObject(bout.toByteArray());
    catch (IOException e) {
    System.out.println("Serialization error: " + e.getMessage());
    * Deserializes a ByteLongObject to a Java object.
    public static Object deserialize(ByteLongObject blob) {
    if (blob == null) {
    return null;
    else {
    try {
    ByteArrayInputStream bin =
    new ByteArrayInputStream(blob.getByteArray());
    ObjectInputStream ob_in = new ObjectInputStream(bin);
    Object ob = ob_in.readObject();
    ob_in.close();
    return ob;
    catch (ClassNotFoundException e) {
    System.out.println("Class not found: " + e.getMessage());
    catch (IOException e) {
    System.out.println("De-serialization error: " + e.getMessage());
    so if you want it to translate it use it something like :
    private Object translateObjectType(Object ob) {
    return MyObjectTranslator.translate(ob);
    and when you wana retrive it use it like :
    Object ds = MyObjectTranslator .deserialize((ByteLongObject) ob);

  • BlazeDS serialization question

    I recently came into a situation when sending a nested object from Java to Flex via a HashMap the Objects were null. More precisely:
    final Map<Integer, List<String>> tempMap = new HashMap<Integer, List<String>>();
    would send the keys as integers but the values were all null.
    But when sending the same with String keys:
    final Map<String, List<String>> tempMap = new HashMap<String, List<String>>();
    the objects came thru.
    Are there any restrictions in BlazeDS serialization when using complex types as keys?

    Just in case anyone is still looking for an answer to this issue, I just ran into the same problem.  During my investigation, I learned that BlazeDS serialization is expecting only String key values for Map objects.   Since the Map coming in has Integer keys, the key is changed to a string by the serialization.  At that point, the value cannot be obtained and serialized.  Change the Integer key to a String and it works.  Here is the site that helped me get it working.
    http://agricola-online.blogspot.com/2010/01/hibernate-blazeds-java-5-enum-and-flex.html

Maybe you are looking for