1 / 36

Java Beans

Java Beans. JB – tehnologie utilizat ă pentru construirea de componente reutilizabile, autonome , independente de platformă şi asamblabile Caracteristici Persistenţa . Prin mecanismul de serializare se asigură salvarea stării unui obiect bean şi restaurarea sa

maude
Download Presentation

Java Beans

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Beans JB – tehnologie utilizată pentru construirea de componente reutilizabile, autonome , independente de platformă şi asamblabile Caracteristici • Persistenţa. Prin mecanismul de serializare se asigură salvarea stării unui obiect bean şi restaurarea sa • Comunicarea prin evenimente. Se utilizează mecanismul sursă-ascultător pentru a comunica intre două obiecte bean • Reflexia (introspecţia). Se utilizează mecanismul Java-Reflection pentru a afla informaţii despre obiecte la momentul execuţiei • Reguli de denominare • Constructor public fără parametrii • Definire de proprietăţi • Metode publice normalizate de acces utilizând prefixe: set, get, is

  2. Proprietăţi Sunt date (primitive sau obiecte) care dau starea unui obiect bean. Tipuri de proprietăţi: • Proprietăţi simple • Proprietăţi indexate • Proprietăţi legate • Proprietăţi cu constrângeri Proprietățile simple sunt atribute care au asociate metode set, get, is. private <tip><nume>; ... public void set<nume>(<tip> val); public <tip> get<nume>(); Metodele set nu suntobligatorii. Pentruatributelebooleanaccesul se face si prin: public boolean is<nume>();

  3. Proprietatile indexate corespund atributelor de tip masiv: private <tip>[] nume; ... public <tip>[] get<nume>(); public void set<nume>(<tip>[] val); public <tip> get<nume>(int index); public void set<nume>(int index, <tip> val); Proprietatile legate sunt proprietati care genereaza un eveniment la schimbarea valorilor lor. Aceste evenimente pot fi interceptate de obiecte din clase special - ascultatori. Implementare eveniment: public class PropertyChangeEvent extends EventObject; public PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue); // source - obiectul care contine proprietatea pentru care se face notificarea (ii se schimba valoarea), propertyName - numele proprietatii, oldValue, newValue - valoriile veche si noua

  4. Metode ale clasei: public Object getOldValue(); public Object getNewValue(); public String getPropertyName(); Sursa evenimentelor PropertyChangeEvent o constituie obiectele care contin proprietatile legate. Un astfel de obiect trebuie sa aiba metode care sa permita inregistrarea/stergerea de ascultatori pentru evenimentele PropertyChangeEventgenerate. Implementarea ascultatorilor se face prin interfata: public interface PropertyChangeListener extends EventListener; void propertyChange(PropertyChangeEvent evt) ; // Metoda de implementat Exemplu de adaugare/stergere ascultatori: public void addPropertyChangeListener(PropertyChangeListener l){ ... } public void removePropertyChangeListener(PropertyChangeListener l){ ... }

  5. Proprietati legate - mecanismul de notificare In plus fata de simpla inregistrare a ascultatorilor, un obiect cu proprietati legate trebuie sa furnizeze un mecanism pentru crearea efectiva a ascultatorilor si notificarea lor la crearea de evenimente. Acest mecanism este implementat de clasa: public class PropertyChangeSupport extends Object implements Serializable; Constructor: public PropertyChangeSupport(Object sourceBean); // se specifica beanul asociat - cel pentru care se efectueaza suportul Metode: public void firePropertyChange(String propertyName, Object oldValue, Object newValue); //raporteaza schimbarea unei proprietati public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue); //idem pentru o proprietate indexata

  6. public void addPropertyChangeListener(PropertyChangeListener listener); // Adaugare ascultator pentru modificarea proprietatilor public void removePropertyChangeListener(PropertyChangeListener listener); // Stergere ascultator

  7. Proprietati cu constrangeri Prin mecanismul de constrangere, modificarea valorilor unor proprietati poate fi impiedicata de terte obiecte, printr-un fel de "veto". Din punct de vedere tehnic, mecanismul este asemanator celui de notificare: - sunt inregistrati ascultatori de veto; - se face notificare de veto si se arunca o exceptie de tip PropertyVetoException; - suportul este asigurat de clasa: public class VetoableChangeSupport extends Object implements Serializable; public VetoableChangeSupport(Object sourceBean); public void addVetoableChangeListener(VetoableChangeListener listener); public void removeVetoableChangeListener(VetoableChangeListener listener); public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) throws PropertyVetoException;

  8. Java API - Introspector public class Introspector extends Object; Este o clasa utilitara care pune la dispozitie un instrument de inspectare a claselor bean (proprietati, metode, evenimente). Informatiile sunt furnizate prin intermediul obiectelor BeanInfo. Obtinere BeanInfo: public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException; Investigare: PropertyDescriptor[] getPropertyDescriptors(); MethodDescriptor[] getMethodDescriptors(); EventSetDescriptor[] getEventSetDescriptors();

  9. Clasele Descriptor public class FeatureDescriptor extends Object; // este utilizata pentru obtinerea unor informatii commune despre proprietati, metode si evenimente in cadrul unui bean Metode: public String getName(); // numele programmatic al proprietatii public void setName(String name); public class PropertyDescriptor extends FeatureDescriptor; // descrierea proprietatilor Constructori: public PropertyDescriptor(String propertyName, Class<?> beanClass) throws IntrospectionException; // este conditionat de conventia set-get-is public PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName) throws IntrospectionException; // pentru scriere/citire se poate trece null

  10. Metode: public Class<?> getPropertyType(); // tipul proprietatii public Method getReadMethod(); // intoarce metoda read public void setReadMethod(Method readMethod) throws IntrospectionException; // stabileste metoda read public Method getWriteMethod(); // metoda write public void setWriteMethod(Method writeMethod) throws IntrospectionException; public class MethodDescriptor extends FeatureDescriptor; Metode: public Method getMethod(); public ParameterDescriptor[] getParameterDescriptors();

  11. public class EventSetDescriptor extends FeatureDescriptor; Metode: public Class<?> getListenerType(); public Method getAddListenerMethod(); public Method getRemoveListenerMethod();

  12. Fisiere si fluxuri de date

  13. FISIERE public class File extends Object implements Serializable, Comparable File(String cale); File(String dir, String fis); File(File dir,String fis); public String getPath(); public String getAbsolutePath(); public String getCanonicalPath() throws IOException; public boolean exists(); public boolean isDirectory(); public boolean isFile(); public long length(); public String[] list(); boolean canRead(); boolean canWrite(); boolean delete(); public File[] listFiles(); boolean renameTo(File numeNou); (Exp - TraversareRecursiva) (Exp - ComparatorDirectoare)

  14. public class RandomAccessFile extends Object implements DataOutput, DataInput, Closeable RandomAccessFile(String fis,String mod) throws FileNotFoundException; // mod: “r”,”rw” RandomAccessFile(File fis,String mod) throws FileNotFoundException; long getFilePointer() throws IOException; long length() throws IOException; void seek(long poz) throws IOException; int read() throws IOException; int read(byte dst[]) throws IOException; int read(byte dst[],int index,int lung) throws IOException; void write(int b) throws IOException; void write(byte srs[]) throws IOException; void write(byte srs[],int index,int lung) throws IOException; void close() throws IOException;

  15. Filtrarea fisierelor public final class FileNameExtensionFilter extends FileFilter public FileNameExtensionFilter(String description, String... extensions); // Descrierea asociata filtrarii si extensiile public boolean accept(File f); // intoarce true daca extensia fisierului coincide cu una din extensiile filtrului sau daca f este un director apartinator public String getDescription(); // intoarce descrierea asociata public String[] getExtensions(); //intoarce lista extensiilor asociate public class JFileChooser extends JComponent implements Accessible public JFileChooser() public JFileChooser(String currentDirectoryPath) public JFileChooser(File currentDirectory)

  16. public File getCurrentDirectory() public void setFileFilter(FileFilter filter) public FileFilter getFileFilter() public File getSelectedFile() public void setSelectedFile(File file) public File[] getSelectedFiles() public void setSelectedFiles(File[] selectedFiles) public int showOpenDialog(Component parent) throws HeadlessException public int showSaveDialog(Component parent) throws HeadlessException; Rezultat: •JFileChooser.CANCEL_OPTION •JFileChooser.APPROVE_OPTION •JFileChooser.ERROR_OPTION HeadlessException - Apare când un cod dependent de un echipament este apelat într-un mediu care nu contine echipamentul.

  17. Ierarhia claselor de fluxuri binare – fluxuri de intrare (intrare) InputStream ByteArrayInputStream FileInputStream FilterInputStream BufferedInputStream DataInputStream (implements DataInput) LineNumberInputStream PushbackInputStream ObjectInputStream (implements ObjectInput) PipedInputStream SequenceInputStream StringBufferInputStream

  18. public abstract class InputStream extends Objectimplements Closeable • public int available() throws IOException • public void close() throws IOException • public abstract int read() throws IOException • public int read(byte[] b) throws IOException • public int read(byte[] b, int off, int len) throws IOException

  19. public class FileInputStream extends InputStream FileInputStream(String cale) throws FileNotFoundException; FileInputStream(File fisier) throws FileNotFoundException; int read() throws IOException; int read(byte dst[]) throws IOException; int read(byte dst[],int index,int lung) throws IOException; int available() throws IOException; void close() throws IOException; long skip(long nrOcteti) throws IOException;

  20. Interfaţa DataInput - Citirea datelor structurate public void readFully(byte[] b, int off, int len) throws IOException public void readFully(byte[] b) throws IOException public boolean readBoolean() throws IOException public byte readByte() throws IOException public int readUnsignedByte() throws IOException public short readShort() throws IOException public int readUnsignedShort() throws IOException public char readChar() throws IOException public int readInt() throws IOException public long readLong() throws IOException public float readFloat() throws IOException public double readDouble() throws IOException public StringreadLine() throws IOException public StringreadUTF() throws IOException public int skipBytes(int n) throws IOException

  21. public class DataInputStream extends FilterInputStream implements DataInput protected InputStream in; Public DataInputStream(InputStream fluxIntrare); public static final StringreadUTF(DataInput in) throws IOException

  22. Ierarhia claselor de fluxuri binare – fluxuri de iesire (scriere) OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream BufferedOutputStream DataOutputStream (implements DataOutput) PrintStream ObjectOutputStream (implements ObjectOutput) PipedOutputStream

  23. public abstract class OutputStream extends Objectimplements Closeable, Flushable • public abstract void write(int b) throws IOException • public void write(byte[] b) throws IOException • public void write(byte[] b, int off, int len) throws IOException • public void flush() throws IOException • public void close() throws IOException

  24. public class FileOutputStream extendsOutputStream FileOutputStream(String cale) throws FileNotFoundException; FileOutputStream(File fisier) throws FileNotFoundException; void write(int b) throws IOException; void write(byte srs[]) throws IOException; void write(byte srs[],int index,int lung) throws IOException; void close() throws IOException; public void flush() throws IOException

  25. public class DataOutputStream extends FilterOutputStream implements DataOutput protected OutputStream out protected int written; // contor al numarului de octeti scris la un moment dat public DataOutputStream(OutputStream fluxIesire); public final int size(); // intoarce valoarea lui written

  26. Ierarhia claselor de fluxuri caracter – fluxuri de intrare (citire) Unitatea transferabila este caracterul unicode. Sunt fluxuri sincrone care folosesc un obiect lock pentru sincronizare. Reader BufferedReader LineNumberReader CharArrayReader FilterReader InputStreamReader FileReader PipedReader StringReader

  27. Ierarhia claselor de fluxuri caracter – fluxuri de iesire (scriere) Writer BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter FileWriter PipedWriter PrintWriter StringWriter

  28. public abstract class Readerextends Object Campuri: • protected Object lock ; // obiect folosit in sincronizare Metode: • public int read() throws IOException • public int read(char[] cbuf) throws IOException • public abstract int read(char[] cbuf, int off, int len) throws IOException • public boolean ready() throws IOException

  29. public class FileReader extends InputStreamReader FileReader(File fis) throws FileNotFoundException; FileReader(String fis) throws FileNotFoundException;

  30. public class InputStreamReaderextends Reader Este un flux de legatura cu fluxurile binare. Legatura se face prin codificare. Fata de fluxurile character contine in plus informatii de codificare: public StringgetEncoding() Constructorii primesc si un parametru de tip Charset reprezentand codificarea: public InputStreamReader(InputStream in) public InputStreamReader(InputStream in, String charsetName) throws UnsupportedEncodingException public InputStreamReader(InputStream in, Charset cs) public InputStreamReader(InputStream in, CharsetDecoder dec)

  31. public abstract class Writer extends Objectimplements Appendable, Closeable, Flushable • protected Object lock; // sincronizare - idem Reader • public void write(int c) throws IOException • public void write(char[] cbuf) throws IOException • public abstract void write(char[] cbuf, int off, int len) throws IOException • public void write(String str) throws IOException • public void write(String str, int off, int len) throws IOException • public Writerappend(char c) throws IOException • public Writerappend(CharSequence csq, int start, int end) throws IOException

  32. public class FileWriter extends Writer FileWriter(File fis) throws FileNotFoundException; FileWriter(String fis) throws FileNotFoundException; void write(int ch) throws IOException; void write(byte srs[],int index,int lung) throws IOException; void write(String srs,int index,int lung) throws IOException;

  33. public class OutputStreamWriter extends Writer Flux de legatura ca si InputStreamReader. public StringgetEncoding(); // intoarce tipul de codare public OutputStreamWriter(OutputStream out) public OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException public OutputStreamWriter(OutputStream out, Charset cs) public OutputStreamWriter(OutputStream out, CharsetDecoder dec)

  34. Fluxuri de nivel superior pentru manipulare linii (citeste/scrie o linie - pana la intalnirea caracterelor de sfarsit de linie la citire, sau scriind caracterele de sfarsit de linie la scriere) BufferedReader  BufferedReader(Reader flux); BufferedReader(Reader flux, int marime); String readLine() throws IOException; BufferedWriter BufferedWriter(Writer flux); BufferedWriter(Writer flux,int marime); void newLine() throws IOException;

  35. PrintWriter Flux de nivel superior pentru scriere date structurate in fisiere text. PrintWriter(Writer flux); PrintWriter(Writer flux, boolean autoFlush); - trimitere automata a liniei PrintWriter(OutputStream flux); PrintWriter(OutputStream flux, boolean autoFlush); void print(...); void println(...);

More Related