Serializing a class that implements the Singleton pattern

Hello,
I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
I have a class that implements the singleton pattern. It's definition is as follows:
public class JCOption implements Serializable {
  private int x = 1;
  private static JCOption option = new JCOption();
  private JCOption() {}
  public static JCOption getOption() { return option; }
  public int getX() { return x; }
  public void setX(int x) { this.x = x; }
  public static void main(String args[]) throws IOException {
    JCOption opt = JCOption.getOption();
    opt.setX(10);
    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
    encoder.setPersistenceDelegate(opt.getClass(),  new JCOptionPersistenceDelegate());
    encoder.writeObject(opt);
    encoder.close();
}Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
  protected Expression instantiate(Object oldInstance, Encoder out) {
       Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
        return expression;
  }The problem is that the resulting XML file only contains the following lines:
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
        <object class="JCOption" property="option"/>
    </java> so there is no trace of the property x.
Thank you in advance for your answers.

How about this:
import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.Expression;
import java.beans.Statement;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class JCOption {
    private int x = 1;
    private static JCOption option = new JCOption();
    private JCOption() {}
    public static JCOption getOption() { return option; }
    public int getX() { return x; }
    public void setX(int x) { this.x = x; }
    public static void main(String args[]) throws IOException {
      JCOption opt = JCOption.getOption();
      opt.setX(10);
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      XMLEncoder encoder = new XMLEncoder( os );
      encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
      encoder.writeObject(opt);
      encoder.close();
      System.out.println( os.toString() );
class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
    protected Expression instantiate(Object oldInstance, Encoder out) {
        return new Expression(
                oldInstance,
                oldInstance.getClass(),
                "getOption",
                new Object[]{} );
    protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
        super.initialize( type, oldInstance, newInstance, out );
        JCOption q = (JCOption)oldInstance;
        out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
}   Output:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_06" class="java.beans.XMLDecoder">
<object class="JCOption" property="option">
  <void property="x">
   <int>10</int>
  </void>
</object>
</java>

Similar Messages

  • Implementing the Singleton pattern

    Has anyone implemented the singleton pattern in Forte? A singleton is simply ensuring that there is one unique instance of a class. In other OO languages I would create a class method which would use a class variable to hold onto the unique instance. Since forte doesn't have either of these (class methods or variables), I'm not sure how to do it. I thought of using named objects, but it seems like a heavy implementation. Any ideas.

    An SO with its shared=TRUE and anchored=TRUE?
    Venkat J Kodumudi
    Price Waterhouse LLP
    Internet: [email protected]
    Internet2: [email protected]
    -----Original Message-----
    From: [email protected] [SMTP:[email protected]]
    Sent: Monday, February 02, 1998 1:09 PM
    To: Venkat Kodumudi
    Subject: Implementing the Singleton pattern
    To: [email protected] @ Internet
    cc:
    From: [email protected] @ Internet
    Date: 02/02/98 12:36:02 PM
    Subject: Implementing the Singleton pattern
    Has anyone implemented the singleton pattern in Forte? A singleton is
    simply
    ensuring that there is one unique instance of a class. In other OO
    languages I
    would create a class method which would use a class variable to hold
    onto the
    unique instance. Since forte doesn't have either of these (class
    methods or
    variables), I'm not sure how to do it. I thought of using named
    objects, but it
    seems like a heavy implementation. Any ideas.

  • Reflect the class that implements Runnable

    Hi,
    I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
    I am wondering is it possible at all to start a new thread on a reflected class?
    thanks in advance.
    {              Class refClass = Class.forName(className);
    String methodName = "start";
    Class[] types = new Class[1];
    types[0] = Class.forName("java.util.HashMap");
    Constructor cons = refClass.getConstructor(types);
    Object[] params = new Object[5];
    params[0] = new HashMap();
    Method libMethod = refClass.getMethod(methodName, null);
    libMethod.invoke(objType, null); }

    Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
    In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
    But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
    Runnable r = // some object which implements Runnable
    new Thread(r).start();Not what you wanted? Go ahead and clarify then.

  • Trying to implement the Builder pattern with inheritance

    This is just a bit long, but don't worry, it's very understandable.
    I'm applying the Builder pattern found in Effective Java (J. Bloch). The pattern is avaiable right here :
    http://books.google.fr/books?id=ka2VUBqHiWkC&lpg=PA15&ots=yXGmIjr3M2&dq=nutritionfacts%20builder%20java&pg=PA14
    My issue is due to the fact that I have to implement that pattern on an abstract class and its extensions. I have declared a Builder inside the base class, and the extensions specify their own extension of the base's Builder.
    The abstract base class is roughly this :
    public abstract class Effect extends Trigger implements Cloneable {
        protected Ability parent_ability;
        protected Targetable target;
        protected EffectBinder binder;
        protected Effect(){
        protected Effect(EffectBuilder parBuilder){
            parent_ability = parBuilder.parent_ability;
            target = parBuilder.target;
            binder = parBuilder.binder;
        public static class EffectBuilder {
            protected Ability parent_ability;
            protected Targetable target;
            protected EffectBinder binder;
            protected EffectBuilder() {}
            public EffectBuilder(Ability parParentAbility) {
                parent_ability = parParentAbility;
            public EffectBuilder target(Targetable parTarget)
            { target = parTarget; return this; }
            public EffectBuilder binder(EffectBinder parBinder)
            { binder = parBinder ; return this; }
        // etc.
    }And the following is one of its implementation :
    public class GainGoldEffect extends Effect {
        private int gold_gain;
        public GainGoldEffect(GainGoldEffectBuilder parBuilder) {
            super(parBuilder);
            gold_gain = parBuilder.gold_gain;
        public class GainGoldEffectBuilder extends EffectBuilder {
            private int gold_gain;
            public GainGoldEffectBuilder(int parGoldGain, Ability parParentAbility) {
                this.gold_gain = parGoldGain;
                super.parent_ability = parParentAbility;
            public GainGoldEffectBuilder goldGain(int parGoldGain)
            { gold_gain = parGoldGain; return this; }
            public GainGoldEffect build() {
                return new GainGoldEffect(this);
        // etc.
    }Effect requires 1 parameter to be correctly instantiated (parent_ability), and 2 others that are optional (target and binder). Implementing the Builder Pattern means that I won't have to rewrite specific construcors that cover all the combination of parameters of the Effect base class, plus their own parameter as an extension. I expect the gain to be quite huge, as there will be at least a hundred of Effects in this API.
    But... in the case of these 2 classes, when I'm trying to create the a GoldGainEffect like this :
    new GainGoldEffect.GainGoldEffectBuilder(1 , locAbility).goldGain(5);the compiler says "GainGoldEffect is not an enclosing class". Is there something wrong with the way I'm trying to extend the base Builder ?
    I need your help to understand this and find a solution.
    Thank you for reading.

    The GainGoldEffectBuilder class must be static.
    Otherwise a Builder would require a GainGoldEffect object to exist, which is backwards.

  • The XElement class explicitly implements the IXmlISerializable interface?

    I see a sentence on a training book.
    "The XElement class explicitly implements the IXmlSerializable
    interface, which contains the GetSchema, ReadXml, and
    WriteXml methods so this object can be serialized."
    I don't understand it. From
    the example, explicitly implements the IXmlSerializable interface is from a custom class rather than XElement class. Is
    MSDN wrong?

    I mean in the stackoverflow example,the class is a customized one "MyCalendar:IXmlSerializable"
    public class MyCalendar : IXmlSerializable
    private string _name;
    private bool _enabled;
    private Color _color;
    private List<MyEvent> _events = new List<MyEvent>();
    public XmlSchema GetSchema() { return null; }
    public void ReadXml(XmlReader reader)
    If XElement is a class that implements IXmlSerializable, what is the detail then?
    public class XElement : IXmlSerializable
    public XmlSchema GetSchema() { *detail*?; }
    public void ReadXml(XmlReader reader){*detail*?}
    Any source code of XElement class?

  • Why the singleton pattern used rather than static things?

    class Single
        private Single() {}
        private void print() { System.out.println("Foo~"); }
        private static Single one = new Single();
        public static void print() { one.print(); }
    class Stat
        public static void print() { System.out.println("Foo~"); }
    }What's the different?? What is the benefit of the singleton one?

    There is no practical difference - because, in fact, that is not the singleton pattern!
    A singleton would look like:
    class Singleton {
        private Singleton() {}
        public void print() { System.out.println("Foo~"); }
        private static Singleton instance = new Singleton();
        public static Singleton getInstance() { return instance; }
    }The benefit of this pattern is, that your client code doesn't have to know that there is only one instance (getInstance could return another instance for every call) or of which actual type it is (getInstance could return an instance of any Subclass of Singleton).
    See http://c2.com/cgi/wiki?SingletonPattern for more information on the pattern.

  • How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file?

    How can we send only one message to a WCF service at a time? How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file? Can we do it by Host throttling?

    Hi Pawan,
    You need to use WCF-Custom adapter and add the ServiceThrottlingBehavior service behavior to a WCF-Custom Locations.
    ServiceThrottlingBehavior.MaxConcurrentCalls - Gets or sets a value that specifies the maximum number of messages actively processing across a ServiceHost. The MaxConcurrentCalls property specifies the maximum number of messages actively
    processing across a ServiceHost object. Each channel can have one pending message that does not count against the value of MaxConcurrentCalls until WCF begins to process it.
    Follow MSDN-
    http://msdn.microsoft.com/en-us/library/ee377035%28BTS.10%29.aspx
    http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx
    I hope this helps.
    Rachit
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Abstract Class that implements Comparable

    I am trying to understand how a comparable interface works with an abstract class. Any help is greatly appreciated.
    I have a class ClassA defined as follows:
    public abstract class ClassA implements Comparable I have a method, compareTo(..), within ClassA as follows:
    public int compareTo(Object o) I have a sub-class ClassB defined as follows:
    public class ClassB extends ClassAI am receiving a compile error:
    Class must implement the inherited abstract method packagename.ClassA.compareTo(Object)
    Should or can the compareTo be abstract in ClassA and executed in ClassB? Just not sure how this works.

    ???? if you are inheriting from an abstract class your subclass must implement methods that were declared in the parent (abstract) class but not implemented
    When in doubt, refer to the Java Language Specification..

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Transform a class that implements JPanel into a bean.

    I'd to create a bean, from a class that implements JPanel, that in fact is a custom component.
    How can I create a bean?
    I have absolutely no idea about beans.
    What can make beans for me?
    I know a lot about the theory of ejb, is this what I need?
    I'm quite confused, please make me see the light!!!!!
    Thanks.

    Hi Daniel!
    To answer your question short as possible:
    Java -Beans are reusable code - components,
    similar to VB Active -X components,
    which you can use when developing your own
    applications.
    Beans can have a graphic user interface, so you
    can use builder tools like JBuilder or Beanbox
    to show them graphically in a designer.
    You can modify them about their properties,
    mostly shown in a special property window of a
    builder tool.
    It's really not very hard to create your own beans,
    the only thing you have to do is to pack all the
    classes which make the bean into a jar file.
    Then you can import the bean with the builder
    and it will be shown.
    The jar manifest file needs to look like for example:
    Manifest-Version: 1.0
    Name: BeanClock.class
    Java-Bean: True
    All the properties are implemented by public property-get
    and property-set methods, in order to show them in the property window.
    Java is doing that by introspection.
    Hope, this makes it a little bit clearer for you!

  • HELP?! a class that implements .....  : java.util.Vector

    My instructions say this:
    In the constructor, create the collection object (Since java.util.List is an interface, you will need to instantiate a class that implements this interface: java.util.Vector or java.util.LinkedList or java.util.ArrayList).
    I know, this IS a homework assignment - I am not sure how to go about this. I DO have code so far up to this point, can anyone help?
    import dLibrary.*;
    import java.awt.Color;
    * @author Rob
    * @version 8/18/03
    public class PhrasesII extends A3ButtonHandler
            private A3ButtonWindow win;
            private ATextField stringAcceptor;
            private ALabel listOstrings;
            private ALabel inputString;
            private ALabel status;
            private java.awt.List display;
            private java.util.List collection;
    public PhrasesII()
            win = new A3ButtonWindow(this);
            stringAcceptor= new ATextField (50,420,200,25);
            stringAcceptor.place(win);
            listOstrings = new ALabel(100, 10, 100, 380);
            listOstrings.setFontSize(10);
            listOstrings.setText("List of Strings:");
            listOstrings.place(win);
            inputString = new ALabel(50,400,200,25);
            inputString.setFontSize(10);
            inputString.setText("Input String:");
            inputString.place(win);
            display = new java.awt.List();
            display.setLocation(200, 100);
            display.setSize(200, 250);
            display.setBackground(Color.lightGray);
            win.add(display, 0);
            win.setLeftText("Save");
            win.setMidText("Display");
            win.setRightText("Discard");
            win.repaint();
      public void leftAction()
        public void midAction()
        public void rightAction()

    I am getting a " can't resolve symbol" when I do thisYou have to either import java.util.ArrayList or specify it fully, e.g., "new java.util.ArrayList()".
    Is that the line that is causing you problems? The error message should give the line number.
    my instructions also say I have to use "interface
    java.util.List when declaring your reference" so I am
    confused about using "= new ArrayList();"What they're saying is that you want code like this:
    private java.util.List frogs;    // this is the reference declaration
    //... later on...
    frogs = new java.util.ArrayList();  // this isn't a declarationWhat this means is that when you declare a field or variable, you should declare its type to be an interface.
    But when you actually instantiate a value for that variable, then you should use a concrete class that implements that interface. (You have to; interfaces can't be instantiated.)
    This is good programming style for reasons I don't have the space to explain here.

  • Importing classes that implement jsp tags

              I was making a custom JSP tag library. The tag functionality was implemented in
              a class called, lets cay ClassA. I made the tld file and put it under the WEB-INF
              directory. The class which implemented the functionality was placed under WEB-INF/classes
              directory. I had the imported the tag library using the taglib directive. I was
              getting an error which said "cannot resolve symbol". But when I in the JSP file
              I imported the class file which implemented the taglib functionality the error
              vanished. Is it necessary to import the class files even if the taglib is imported.
              The documentation does not say so. Or is there some configuration I have to make.
              

    I think was a side effect of the .jsp changing redeploys the web app in 6.0.
              When the web app was redeployed your directory structure was reread and thus
              it found your .tld.
              Sam
              "bbaby" <[email protected]> wrote in message
              news:3b422db7$[email protected]..
              >
              > I was making a custom JSP tag library. The tag functionality was
              implemented in
              > a class called, lets cay ClassA. I made the tld file and put it under the
              WEB-INF
              > directory. The class which implemented the functionality was placed under
              WEB-INF/classes
              > directory. I had the imported the tag library using the taglib directive.
              I was
              > getting an error which said "cannot resolve symbol". But when I in the JSP
              file
              > I imported the class file which implemented the taglib functionality the
              error
              > vanished. Is it necessary to import the class files even if the taglib is
              imported.
              > The documentation does not say so. Or is there some configuration I have
              to make.
              >
              >
              

  • Java API that implements the SSH, SFTP and Telnet protocols

    Hi,
    I'm looking for a Java API that implements the SSH, SFTP and Telnet protocols. Does anyone have a suggestion?
    Any Suggestions are really appreciated ?
    Thanks,
    Avin

    I believe SSH and telnet are used for interactive command line sessions, don't know how you want to use them in a program.

  • CV04N-Searching across multiple classes that have the same characteristics

    In CV04N- is there a way to search across mutliple classes that have the same characteristics?
    For example I created 3 new class types each assinged to a new class, each class having the same characteristics.
    Say if I have a characterisitics called Contract Name.  I need to be able to search for a contract name across all 3 classes.
    The search results in CV04N defaults to class type 017 so it only shows characterisitcs relate to that type, Is there a way to get the characteristics for the new created class types to show?
    I know in CV04N you can only search one class type and class at a time.
    Does anyone know of a way to fulfill these requirements, without creating a customized report?

    Hi Jenny,
    The answer for this question is that:
    1. The class 017 document management in cv 04n is SAP standard class .It's totally different than the new class created by you.
    2. The new class in CL02 you are creating is for a perticular document type. When you assign a characteristic (contract name) to this new class ,it appears in additional data field as contract name.
    3. Now you can make a search with only Contract name filed and the report will be displayed with all document types having this characteristic (Contract name) is assigned. Thus you can find the classes(document types)thru characteristic(contract name).
    I hope this will resolve the query. And you will get clarified between two classes( i.e. 017 and new classes in DMS).You can say them as subclassed under 017 class.
    Regards,
    Ravindra

  • How define a global variable in a class that all the methods will recognize

    hi friends,
    i need to define a global variable in a class that all the methods will recognize it.
    any suggestions?
    thanks,
    dana.

    Dera Dana,
    In se24, create your own "Z" class.
    Open the Attributes tab.
    Insert your variable in the declaration part.
    EQ:
    Attribute     Level                       Visibility   Typing      Associated Type         Description        
    ITAB     Instance Attribute     Public     Type     Structure name     Description
    In the Layout of View page,
    <phtmlb:formLayoutDropDownListBox id                = "Dropdown"
                                              label             = "Drop Down"
                                              table             = "<%= controller->Itab %>"
                                              nameOfKeyColumn   = "CODE"
                                              nameOfValueColumn = "VALUE"
                                              selection         = "<%= controller->feild to be selected %>"
                                               />
    Hope this will be helpful
    Regards,
    Gokul.N

Maybe you are looking for

  • How to set group contacts in nokia asha 305

    how to  set group contacts  in nokia asha 305....thank u......

  • Adobe CS4 OpenGL issues with 10.6.2 and Intel GMA950 video card

    I just upgraded to Adobe CS4 and in PS I cannot enable OpenGL. I'm running 10.6.2 on a Macbook with the Intel GMA950 video card. I was wondering if 10.6.2 does not have the relevant drivers for CS4 to recognize this chipset or that since the video ca

  • How to use a c file in LabVIEW

    Hi All, I have a c file which communicates through serial port and J1850 protocol. I want to use the C file in labview and do the communication through serial port. Can any one give me an idea how I have to use the c file in LabVIEW. Thank you.! ----

  • 6500 classic...i have a problem

    basically, my fone was laying there and somebody phoned me so it rang. i didnt pick up the call, and straight after the person hung up, the screen went blank. the light was still on but the screen was blank. i could see the battery life symbol at the

  • How can I view all emails (regardless of account)

    On my Mac, I can easily view all of my inboxes at once for the 3 separate mail accounts I have (work, home and one other). On the iPhone, it seems that I have to keep going back up to the top of the Mail UI and back down into each mail account in ord