API java : XMLEncoder


java.beans
Class XMLEncoder

java.lang.Object
  extended by java.beans.Encoder
      extended by java.beans.XMLEncoder

public class XMLEncoder
extends Encoder

The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects. For example, the following fragment can be used to create a textual representation the supplied JavaBean and all its properties:

  1. new FileOutputStream("Test.xml")));
  2. e.writeObject(new JButton("Hello, world"));
  3. e.close();
Despite the similarity of their APIs, the XMLEncoder class is exclusively designed for the purpose of archiving graphs of JavaBeans as textual representations of their public properties. Like Java source files, documents written this way have a natural immunity to changes in the implementations of the classes involved. The ObjectOutputStream continues to be recommended for interprocess communication and general purpose serialization.

The XMLEncoder class provides a default denotation for JavaBeans in which they are represented as XML documents complying with version 1.0 of the XML specification and the UTF-8 character encoding of the Unicode/ISO 10646 character set. The XML documents produced by the XMLEncoder class are:

  • Portable and version resilient: they have no dependencies on the private implementation of any class and so, like Java source files, they may be exchanged between environments which may have different versions of some of the classes and between VMs from different vendors.
  • Structurally compact: The XMLEncoder class uses a redundancy elimination algorithm internally so that the default values of a Bean's properties are not written to the stream.
  • Fault tolerant: Non-structural errors in the file, caused either by damage to the file or by API changes made to classes in an archive remain localized so that a reader can report the error and continue to load the parts of the document which were not affected by the error.

Below is an example of an XML archive containing some user interface components from the swing toolkit:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <java version="1.0" class="java.beans.XMLDecoder">
  3. <object class="javax.swing.JFrame">
  4. <void property="name">
  5. <string>frame1</string>
  6. </void>
  7. <void property="bounds">
  8. <object class="java.awt.Rectangle">
  9. <int>0</int>
  10. <int>0</int>
  11. <int>200</int>
  12. <int>200</int>
  13. </object>
  14. </void>
  15. <void property="contentPane">
  16. <void method="add">
  17. <object class="javax.swing.JButton">
  18. <void property="label">
  19. <string>Hello</string>
  20. </void>
  21. </object>
  22. </void>
  23. </void>
  24. <void property="visible">
  25. <boolean>true</boolean>
  26. </void>
  27. </object>
  28. </java>
The XML syntax uses the following conventions:
  • Each element represents a method call.
  • The "object" tag denotes an expression whose value is to be used as the argument to the enclosing element.
  • The "void" tag denotes a statement which will be executed, but whose result will not be used as an argument to the enclosing method.
  • Elements which contain elements use those elements as arguments, unless they have the tag: "void".
  • The name of the method is denoted by the "method" attribute.
  • XML's standard "id" and "idref" attributes are used to make references to previous expressions - so as to deal with circularities in the object graph.
  • The "class" attribute is used to specify the target of a static method or constructor explicitly; its value being the fully qualified name of the class.
  • Elements with the "void" tag are executed using the outer context as the target if no target is defined by a "class" attribute.
  • Java's String class is treated specially and is written <string>Hello, world</string> where the characters of the string are converted to bytes using the UTF-8 character encoding.

Although all object graphs may be written using just these three tags, the following definitions are included so that common data structures can be expressed more concisely:

  • The default method name is "new".
  • A reference to a java class is written in the form <class>javax.swing.JButton</class>.
  • Instances of the wrapper classes for Java's primitive types are written using the name of the primitive type as the tag. For example, an instance of the Integer class could be written: <int>123</int>. Note that the XMLEncoder class uses Java's reflection package in which the conversion between Java's primitive types and their associated "wrapper classes" is handled internally. The API for the XMLEncoder class itself deals only with Objects.
  • In an element representing a nullary method whose name starts with "get", the "method" attribute is replaced with a "property" attribute whose value is given by removing the "get" prefix and decapitalizing the result.
  • In an element representing a monadic method whose name starts with "set", the "method" attribute is replaced with a "property" attribute whose value is given by removing the "set" prefix and decapitalizing the result.
  • In an element representing a method named "get" taking one integer argument, the "method" attribute is replaced with an "index" attribute whose value the value of the first argument.
  • In an element representing a method named "set" taking two arguments, the first of which is an integer, the "method" attribute is replaced with an "index" attribute whose value the value of the first argument.
  • A reference to an array is written using the "array" tag. The "class" and "length" attributes specify the sub-type of the array and its length respectively.

For more information you might also want to check out Using XMLEncoder, an article in The Swing Connection.

Since:
1.4
See Also:
XMLDecoder, ObjectOutputStream

Constructor Summary
XMLEncoder(OutputStream out)
          Creates a new output stream for sending JavaBeans to the stream out using an XML encoding.
 
Method Summary
 void close()
          This method calls flush, writes the closing postamble and then closes the output stream associated with this stream.
 void flush()
          This method writes out the preamble associated with the XML encoding if it has not been written already and then writes out all of the values that been written to the stream since the last time flush was called.
 Object getOwner()
          Gets the owner of this encoder.
 void setOwner(Object owner)
          Sets the owner of this encoder to owner.
 void writeExpression(Expression oldExp)
          Records the Expression so that the Encoder will produce the actual output when the stream is flushed.
 void writeObject(Object o)
          Write an XML representation of the specified object to the output.
 void writeStatement(Statement oldStm)
          Records the Statement so that the Encoder will produce the actual output when the stream is flushed.
 
Methods inherited from class java.beans.Encoder
get, getExceptionListener, getPersistenceDelegate, remove, setExceptionListener, setPersistenceDelegate
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

XMLEncoder

public XMLEncoder(OutputStream out)
Creates a new output stream for sending JavaBeans to the stream out using an XML encoding.

Parameters:
out - The stream to which the XML representation of the objects will be sent.
See Also:
XMLDecoder.XMLDecoder(InputStream)
Method Detail

setOwner

public void setOwner(Object owner)
Sets the owner of this encoder to owner.

Parameters:
owner - The owner of this encoder.
See Also:
getOwner()

getOwner

public Object getOwner()
Gets the owner of this encoder.

Returns:
The owner of this encoder.
See Also:
setOwner(java.lang.Object)

writeObject

public void writeObject(Object o)
Write an XML representation of the specified object to the output.

Overrides:
writeObject in class Encoder
Parameters:
o - The object to be written to the stream.
See Also:
XMLDecoder.readObject()

writeStatement

public void writeStatement(Statement oldStm)
Records the Statement so that the Encoder will produce the actual output when the stream is flushed.

This method should only be invoked within the context of initializing a persistence delegate.

Overrides:
writeStatement in class Encoder
Parameters:
oldStm - The statement that will be written to the stream.
See Also:
PersistenceDelegate.initialize(java.lang.Class, java.lang.Object, java.lang.Object, java.beans.Encoder)

writeExpression

public void writeExpression(Expression oldExp)
Records the Expression so that the Encoder will produce the actual output when the stream is flushed.

This method should only be invoked within the context of initializing a persistence delegate or setting up an encoder to read from a resource bundle.

For more information about using resource bundles with the XMLEncoder, see http://java.sun.com/products/jfc/tsc/articles/persistence4/#i18n

Overrides:
writeExpression in class Encoder
Parameters:
oldExp - The expression that will be written to the stream.
See Also:
PersistenceDelegate.initialize(java.lang.Class, java.lang.Object, java.lang.Object, java.beans.Encoder)

flush

public void flush()
This method writes out the preamble associated with the XML encoding if it has not been written already and then writes out all of the values that been written to the stream since the last time flush was called. After flushing, all internal references to the values that were written to this stream are cleared.


close

public void close()
This method calls flush, writes the closing postamble and then closes the output stream associated with this stream.


Ces informations proviennent du site de http://java.sun.com

Remarques

Contenu

Le contenu de cette page provient du site de Sun, et est généré depuis un cache sur l'infobrol après certains traitements automatisés. La présentation peut donc différer du document original, mais le contenu aussi. Vous pouvez utiliser ce bouton pour afficher la page originale du site de Sun :

Quels sont les motivations de cette démarche?

Maintenir les pages en cache sur différents sites peut offrir plus de disponibilité.

Chaque page est indexée dans la base de donnée, ce qui permet de retrouver facilement les informations, au moyen des sommaires, du moteur de recherche interne, etc.

Des facilités sont mises en place pour que les membres de l'infobrol puissent effectuer des traductions en français des différents documents. Ceci devrait permettre aux débutants en programmation Java de consulter les API en français s'ils maîtrisent moins bien la langue de Shakespeare. Dans le cas où une traduction a été soumise, elle est disponible au moyen d'un lien en bas de page. Si la traduction a été validée, la page s'affiche par défaut en français, et un lien en bas de page permet d'atteindre la version en anglais.

Le code sur l'infobrol est automatiquement coloré selon la syntaxe, et les différents mots clés sont transformés en liens pour accéder rapidement aux informations.

Vous avez la possibilité de partager vos expériences en proposant vos propres extraits de code en utilisant le bouton "ajouter un commentaire" en bas de page. Si vous visitez simplement l'infobrol, vous avez déjà accès à cette fonction, mais si vous étes membre du brol, vous pouvez en plus utiliser des boutons supplémentaires de mise en forme, dont la coloration automatique de vos extraits de codes.

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

6 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-1134
Document créé le 29/08/06 00:16, dernière modification le Vendredi 17 Juin 2011, 12:12
Source du document imprimé : http://www.gaudry.be/java-api-rf-java/beans/XMLEncoder.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
1,17 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Le rire, comme les essuie-glaces, permet d'avancer même s'il n'arrête pas la pluie.

Gérard Jugnot
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 15:07, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)