Académique Documents
Professionnel Documents
Culture Documents
Bibliography
0-0
V. Granet U.N.S.A.
Le langage Java
Part 1: Bibliography
R
ef
erences
[1] Vincent Granet and Jean-Pierre Regourd.
Aide-Memoire de Java. Dunod, 2 edition,
2008.
[2] Bertrand Meyer. Conception et
Programmation orientees objet. Eyrolles, 2000.
[3] Walter Savitch. Java, an Introduction to
Computer Science and Programming.
Prentice-Hall, 1999.
[4] H.M. Deitel and P.J. Deitel. Java. How to
program. Prentice-Hall, 1998.
Introduction
V. Granet U.N.S.A.
Le langage Java
V. Granet U.N.S.A.
Le langage Java
Part 2: Introduction
Part 2: Introduction
Historique
V. Granet U.N.S.A.
Le langage Java
Part 2: Introduction
V. Granet U.N.S.A.
Inconvenients
langage `a objets
syntaxe simple
notation issue de C
portabilite
API tr`es vaste
javadoc
interfaces graphiques (awt, Swing)
environnement jdk gratuit
V. Granet U.N.S.A.
Part 2: Introduction
Avantages
Le langage Java
Le langage Java
produit industriel
temps dexecution - Interpretation (mais JIT)
API tr`es (trop ?) vaste, difficile `a maitriser
constructions archaques issues de C
temps reel
V. Granet U.N.S.A.
Le langage Java
Part 2: Introduction
Part 2: Introduction
Premi`eres applications
/* ma premi`
e re application Java */
/* * La classe Wc
e crit le nombre de caract`
e res
c l a s s HelloWorld {
public
static
*/
i m p o r t java . io .*;
public
c l a s s Wc {
public
static
t h r o w s IOException
{
i n t nbc = 0; // compteur de caract`eres
w h i l e ( System . in . read () != -1)
/* ma premi`
e re applet Java */
nbc ++;
public
c l a s s HelloWorldApplet e x t e n d s Applet {
} // fin classe Wc
p u b l i c v o i d paint ( Graphics g ) {
g . drawString ( " Hello World ! " , 5 , 25);
}
} // fin classe HelloWorldApplet
V. Granet U.N.S.A.
Le langage Java
Part 2: Introduction
V. Granet U.N.S.A.
Le langage Java
Part 2: Introduction
Principe de compilation
interpretation
$ javac HelloWorld.java
$ java HelloWorld
compilateur Java
source
Java
(.java)
Java
Java
bytecode
Hello World!
fichier
Java
bytecode
$ javac HelloWorldApplet.java
(.class)
$ appletviewer HelloWorldApplet.html
<applet
interprte
Java
</applet>
la variable CLASSPATH
Production code `a la volee (JIT)
V. Granet U.N.S.A.
Le langage Java
10
V. Granet U.N.S.A.
Le langage Java
11
Part 2: Introduction
La documentation
javadoc
produit une documentation en html
traite les commentaires /** */
reconnat des macros :
@author
@version
@param
@return
@see
...
Les types
el
ementaires
$ javadoc Wc.java
$ firefox index.html
V. Granet U.N.S.A.
Le langage Java
12
V. Granet U.N.S.A.
13
Les nombres
Le langage Java
Les booleens
Arithmetique classique
byte (8 bits)
short (16 bits)
int (32 bits)
long (64 bits)
boolean
false et true
operateurs :
!
la negation
la disjonction
la disjonction exclusive
&
la conjection
||
la disjonction conditionnelle
&&
la conjection conditionnelle
i f (i < n && t [ i ]) {
....
3.5e-7
1.5e2
V. Granet U.N.S.A.
Le langage Java
14
V. Granet U.N.S.A.
Le langage Java
15
Les conteneurs
Les caract`eres
char
jeu de caract`eres Unicode sur 16 bits
www.unicode.org
constantes denotees en apostrophes (e.g. a,
4, , etc.)
caract`eres speciaux :
\b \f \n \r \t \\ \
valeur hexadecimale : \uxxxx (e.g. \u0041)
int nbEl`
eves;
double ;
Character
mais conversions implicites (jdk1.5)
Integer i = 5;
c h a r c = new Character ( z );
V. Granet U.N.S.A.
Le langage Java
16
V. Granet U.N.S.A.
Le langage Java
17
Part 4: Les
enonc
es
Les
enonc
es
V. Granet U.N.S.A.
Le langage Java
18
V. Granet U.N.S.A.
Le langage Java
19
Part 4: Les
enonc
es
Part 4: Les
enonc
es
static
{
final
d o u b l e a = StdInput . readDouble () ,
b = StdInput . readDouble () ,
c = StdInput . readlnDouble () ,
r1 , r2 , i1 , i2 , ;
// a6=0, b et c coefficients r
eels de
// l
equation du second degr
e, ax2 + bx + c
public
= ( b * b ) -4* a * c;
static
l o n g factorielle ( l o n g n )
// Ant
ec
edent: n > 0
// Cons
equent: factorielle=n!
l o n g i = 0 , fact = 1;
r2 =
// Invariant : fact=i!
w h i l e (i < n ) {
i1 = i2 = 0;
// (x-r1)(x-r2)=0
i ++;
// fact*i = i!
fact *= i ;
// fact = i!
// (x-(r1+ii1)) (x-(r2+ii2)) = 0
// i=n et fact = i! = n!
return
//
ecrire les racines solutions sur la sortie standard
fact ;
V. Granet U.N.S.A.
Le langage Java
20
V. Granet U.N.S.A.
Le langage Java
21
Objets et Classes
application = collection dobjets
dynamiques en interaction
objet = fournisseur de services utilises
par des clients
programmation par contrat. B. Meyer.
classe = moule `a objets
une classe nest pas un objet (en Java)
un objet est une instance dune classe
attributs et methodes
Les objets
c l a s s Rectangle {
d o u b l e largeur , longueur ;
}
V. Granet U.N.S.A.
Le langage Java
22
V. Granet U.N.S.A.
Le langage Java
23
References
La variable r est une reference a
` lobjet, et non pas
lobjet lui-meme.
Rectangle r;
r = new Rectangle ();
Pb de laffectation, de la comparaison et du
passage de param`etre.
ou
Rectangle q = r ;
largeur
r
rfrence
0.0
longueur
0.0
rfrence
longueur
largeur
r
0.0
rfrence
0.0
V. Granet U.N.S.A.
Le langage Java
24
Le langage Java
25
Les constructeurs
V. Granet U.N.S.A.
automatique en Java
`a la charge du support dexecution
va dans le sens de la securite
Rectangle ( d o u b l e l , d o u b l e L ) {
largeur = l; longueur = L ;
}
Rectangle () {
largeur = longueur = 0.0;
}
V. Granet U.N.S.A.
Le langage Java
26
V. Granet U.N.S.A.
Le langage Java
27
Les methodes
procedures et fonctions
objet = automate `a etats
une procedure modifie letat
une fonction renvoie une description de letat
mod`ele pas toujours possible
notation pointee
r.largeur;
r.p
erim`
etre();
attributs publics
attributs prives
c l a s s Rectangle {
d o u b l e largeur , longueur ;
// modifie la largeur du Rectangle courant
c l a s s Rectangle {
v o i d changerLargeur ( d o u b l e l ) {
p r i v a t e d o u b l e largeur , longueur ;
largeur = l ;
p u b l i c v o i d changerLargeur ( d o u b l e l ) {
// renvoie le p
erim`
etre du Rectangle courant
d o u b l e p
e rim`
e tre () {
// renvoie le p
erim`
etre du Rectangle courant
largeur = l ;
r e t u r n 2 * ( largeur + longueur );
p u b l i c d o u b l e p
e rim`
e tre () {
r e t u r n 2 * ( largeur + longueur );
}
}
V. Granet U.N.S.A.
Le langage Java
28
V. Granet U.N.S.A.
Le langage Java
29
Paquetages(1/2)
Paquetage = ensemble de classes dune meme
thematique (java.awt, java.lang, java.math, ...)
static
i n t partag
e;
static
v o i d uneM
e thode () { ... }
java
applet
awt
javax org
io lang
p a c k a g e monpaquetage ;
des attributs
System.out
p a c k a g e mon . paquetage ;
p a c k a g e java . io ;
Math.PI
Math.exp(13.4)
des methodes
Math.sin(3.14)
StdInput.readInt()
main
V. Granet U.N.S.A.
Le langage Java
30
V. Granet U.N.S.A.
Le langage Java
31
Portees
Paquetages(2/2)
les classes
Notation qualifiee :
defaut
le paquetage
public
partout
defaut
le paquetage
public
partout
private
la classe
protected
classe
sous-classes
Exemples
paquetage
i m p o r t paquetage . classe ;
i m p o r t paquetage .*;
i m p o r t java . awt . Canvas ;
i m p o r t java . io .*;
V. Granet U.N.S.A.
Le langage Java
32
V. Granet U.N.S.A.
Le langage Java
33
est equivalent `
a
V. Granet U.N.S.A.
Le langage Java
34
V. Granet U.N.S.A.
Le langage Java
35
p u b l i c String toString () {
r e t u r n " Rectangle ( " + largeur + " ,"
+ longueur + " )" ;
}
V. Granet U.N.S.A.
Le langage Java
36
V. Granet U.N.S.A.
Le langage Java
37
charAt(int index)
int
indexOf(int ch)
int
int
indexOf(String str)
int
String
substring(int beginIndex)
String
toLowerCase()
String
toUpperCase()
int
compareTo(String s)
boolean
equals(String s)
Les tableaux
V. Granet U.N.S.A.
Le langage Java
38
V. Granet U.N.S.A.
Le langage Java
39
i n t [] t1 = new i n t [ 10 ]; // 10 entiers
Complexe [] t2 = new Complexe [5]; // 5 references
V. Granet U.N.S.A.
Le langage Java
40
V. Granet U.N.S.A.
Le langage Java
41
public
c l a s s Table {
private
i n t [] tab ;
// le g
en
erateur de nombres al
earoires
p u b l i c Table ( i n t n )
// R^
ole: initialise le tableau tab de fa
con al
eatoire
{
i f (n <=0) {
System . err . println ( " taille <= 0 " );
System . exit (1);
}
tab = new i n t [ n ];
f o r ( i n t i = 0; i < tab . length ; i ++)
// les
el
ements tab[0]..tab[i-1] sont
// initialis
es de fa
con al
eatoire
}
} // fin classe Table
V. Granet U.N.S.A.
Le langage Java
42
V. Granet U.N.S.A.
Le langage Java
43
Param`etres de lapplication
p u b l i c v o i d s
e lectionOrdinaire () {
f o r ( i n t i = 0; i < tab . length - 1 ; i ++) {
/* *
* Cette application
e crit sur la sortie standard
i n t min = i;
* ses param`
e tres pass
e s lors de son ex
e cution
*/
c l a s s Echo {
public
static
//
echanger le i`
eme et l
el
ement min
e changer ( min , i );
// e
crire le dernier param`
etre et le passage `
a la ligne
}
}
private void
e changer ( i n t i , i n t j ) {
}
//
echange les valeurs de tab[i] et tab[j]
i n t temp = tab [i ];
tab [ i ] = tab [j ];
tab [ j ] = temp ;
}
V. Granet U.N.S.A.
Le langage Java
44
V. Granet U.N.S.A.
Le langage Java
45
c l a s s Matrice {
// Invariant : this est une matrice (lignes,colonnes)
p r i v a t e \ d o u b l e [][] m;
d o u b l e [][] matriceD = new d o u b l e [m ][ n ];
// le g
en
erateur de nombres al
earoires
Matrice ( i n t l , i n t c )
// R^
ole: cr
eer une matrice (l,c)
// v
erifier que l et c sont > 0
...
m = new i n t [ l ][ c ];
nblgs = l; nbcols = c ;
...
}
V. Granet U.N.S.A.
Le langage Java
46
V. Granet U.N.S.A.
Le langage Java
47
// Cons
equent : renvoie une matrice (n,p)
//
Matrice c =
new Matrice ( t h i s . nblgs ,m . nbcols );
f o r ( i n t i = 0; i < c . nblgs ; i ++)
f o r ( i n t j = 0; j < c . nbcols ; j ++) {
// x 0..i 1, y 0..j 1,
P
k = 1pthis xkm ky
H
eritage
// c x, y =
d o u b l e somme =0;
f o r ( i n t k = 0; k < t h i s . nbcols ; k ++)
somme += t h i s .m [ i ][ k ]* m . m [ k ][ j ];
c . m [i ][ j ] = somme ;
}
r e t u r n c;
}
V. Granet U.N.S.A.
Le langage Java
48
Part 8: H
eritage
V. Granet U.N.S.A.
Le langage Java
49
Part 8: H
eritage
Introduction
public
c l a s s Carr
e {
p r i v a t e d o u b l e cot
e;
p u b l i c Carr
e( double c)
{
cot
e = c;
}
p u b l i c d o u b l e p
e rim`
e tre ()
// R^
ole: retourne le p
erim`
etre du carr
e
{
r e t u r n 4* cot
e;
}
p u b l i c d o u b l e surface ()
// R^
ole: retourne la surface du carr
e
{
r e t u r n cot
e * cot
e;
}
} // fin classe Carre
V. Granet U.N.S.A.
Le langage Java
50
V. Granet U.N.S.A.
Le langage Java
51
Part 8: H
eritage
Part 8: H
eritage
Heritage ou client
relation est-un
relation a-un
mais ...
public
c l a s s Carr
e e x t e n d s Rectangle {
public
p u b l i c Carr
e ( d o u b l e c) {
c l a s s Rectangle {
Point origine ;
s u p e r (c ,c );
...
p u b l i c v o i d changerCot
e ( d o u b l e cot
e) {
// R^
ole: met `
a jour le cot
e
changerLargeur ( cot
e );
changerLongueur ( cot
e );
ou
}
}
public
c l a s s Rectangle e x t e n d s Point {
....
protected
super et super()
la classe Object
le graphe dheritage
heritage = specialisation et extension
V. Granet U.N.S.A.
Le langage Java
52
Part 8: H
eritage
V. Granet U.N.S.A.
Le langage Java
53
Part 8: H
eritage
p u b l i c String toString ()
carr
e de cot
e
egal `
a 6
r e t u r n " rectangle de largeur " + largeur
+ " et de longueur " + longueur ;
}
// Dans la classe Carr
e
p u b l i c String toString ()
{
r e t u r n " carr
e de cot
e
e gal `
a " + largeur ;
}
V. Granet U.N.S.A.
Le langage Java
54
V. Granet U.N.S.A.
Le langage Java
55
Part 8: H
eritage
Part 8: H
eritage
Polymorphisme (1/2)
Rectangle r;
Carr
e c = new Carr
e (3);
r = c; // valide : un carre est rectangle
c = r; // erreur de compilation !
// un rectangle nest pas (forc
ement) un carr
e
V. Granet U.N.S.A.
Le langage Java
56
Part 8: H
eritage
V. Granet U.N.S.A.
Le langage Java
57
Part 8: H
eritage
Liaison dynamique
Polymorphisme (2/2)
Forme
Ellipse
Rectangle
Cercle
Carr
V. Granet U.N.S.A.
Le langage Java
58
V. Granet U.N.S.A.
Le langage Java
59
Part 8: H
eritage
Part 8: H
eritage
public abstract
Carr
c l a s s Forme {
p u b l i c a b s t r a c t i n t p
e rim`
e tre ();
CercledansCarr
p u b l i c a b s t r a c t i n t surface ();
}
V. Granet U.N.S.A.
Le langage Java
60
Part 8: H
eritage
V. Granet U.N.S.A.
Le langage Java
61
Part 8: H
eritage
Interfaces (1/2)
Interfaces (2/2)
c l a s s MaClasse i m p l e m e n t s MonInterface {
public
p u b l i c v o i d uneM
e thode ( i n t x ) {
i n t e r f a c e MonInterface {
static
final
....
i n t uneConstate = 10;
}
a b s t r a c t p u b l i c v o i d uneM
e thode ( i n t x );
}
V. Granet U.N.S.A.
Le langage Java
62
Serializable
Cloneable
Runnable
ActionListener
...
V. Granet U.N.S.A.
Le langage Java
63
Part 8: H
eritage
Part 8: H
eritage
Interfaces et Polymorphisme
I [] table = new I [10];
c l a s s C1 i m p l e m e n t s I {
...
}
c l a s s C2 i m p l e m e n t s I {
...
}
c l a s s C3 i m p l e m e n t s I {
...
}
V. Granet U.N.S.A.
Le langage Java
64
Part 8: H
eritage
V. Granet U.N.S.A.
Le langage Java
65
Part 8: H
eritage
Interfaces et genericite(1/2)
Interfaces et genericite(2/2)
c l a s s Carr
e Comparable e x t e n d s Carr
e
implements
E ltComparable {
p u b l i c b o o l e a n infOu
E gal ( EltComparable o ) {
r e t u r n t h i s . surface () <= (( Carr
e Comparable ) o
}
}
c l a s s PersonneComparable e x t e n d s Personne
ltComparable {
implements E
E gal ( EltComparable o ) {
p u b l i c b o o l e a n infOu
r e t u r n t h i s . taille () <= (( PersonneComparable )
}
}
ltComparable [] t ) {
v o i d tri ( E
gal ( t [j ]) ...
... t [ i ]. infOu E
public
static
}
interface
E ltComparable {
E gal ( EltComparable o );
p u b l i c b o o l e a n infOu
Carr
e Comparable [] t1 =
{ new Carr
e Comparable (3) , ... ,
new Carr
e Comparable (12) , ... };
C . tri ( t1 );
PersonneComparable [] t2 =
{ new PersonneComparable (1.73) , ... ,
new PersonneComparable (1.90) , };
C . tri ( t2 );
V. Granet U.N.S.A.
Le langage Java
66
V. Granet U.N.S.A.
Le langage Java
67
Le probl`eme
Un evenement qui indique une situation anormale
pouvant provoquer un dysfonctionnement du
programme :
pb materiel (E/S, memoire, ...)
pb logiciel (division par zero, non respect des
invariants, ...)
tantque B f a i r e
...
Les exceptions
s i erreur a l o r s
traiter erreur
finsi
...
fintant
V. Granet U.N.S.A.
Le langage Java
68
V. Granet U.N.S.A.
Le langage Java
69
Traitement
Exceptions en Java
Object
Throwable
E1
Error
E2
RuntimeException
E3
ArithmeticException
E4
V. Granet U.N.S.A.
Exception
Le langage Java
IOException
........
........
exception
70
V. Granet U.N.S.A.
Le langage Java
71
clauses try-catch
try {
i n t x = StdInput . readlnInt ();
try {
....
// code normal
...
o. m ();
c a t c h ( IOException e ) {
// la m
ethode m peut provoquer une exception
...
c a t c h ( UneException e ) {
// code de traitement de lexception d
esign
ee par e
...
}
public
static
i n t lirelnInt () {
try {
clause finally
finally {
// code ex
ecut
e quoiquil arrive
r e t u r n lirelnInt ();
}
}
V. Granet U.N.S.A.
Le langage Java
72
V. Granet U.N.S.A.
Le langage Java
73
public
c l a s s MonException e x t e n d s Exception {
i n t code ;
p u b l i c MonException () {
s u p e r ();
}
p u b l i c MonException ( String msg ) {
s u p e r ( msg );
}
RuntimeException
// c 6= 0
p u b l i c v o i d maM
e thode () t h r o w s IOException {
p u b l i c String toString () {
....
}
}
}
V. Granet U.N.S.A.
Le langage Java
74
V. Granet U.N.S.A.
Le langage Java
75
Emettre
une exception
throw (sans s)
p u b l i c v o i d uneM
e thode () {
i f (...) {
throw new ArithmeticException ();
}
...
}
Les entr
ees/sorties
p u b l i c v o i d maM
e thode () t h r o w s MonException {
i f (...) {
throw new MonException (" une erreur " , 3);
}
...
}
Le langage Java
76
V. Granet U.N.S.A.
Fichiers doctets
Declaration :
lecture
ecriture
flots doctets
InputStream
OutputStream
flots de caract`eres
Reader
Writer
methodes de base :
int read()
void write(int)
void close()
paquetage java.io
V. Granet U.N.S.A.
77
Le langage Java
Le langage Java
78
V. Granet U.N.S.A.
Le langage Java
79
new FileInputStream ( in );
DataInputStream et DataOutputstream
readChar, writeChar, readInt, writeInt,
readDouble, writeDouble, ...
fin de fichier exception EOFException
i n t c;
t h r o w s IOException {
DataInputStream is =
os . write ( c );
// EOF de is
is . close ();
i n t nb
E lem = 0;
os . close ();
d o u b l e moy = 0;
try {
while ( true ) {
moy += is . readDouble ();
nb
E lem ++;
}
}
c a t c h ( EOFException e ) {
is . close ();
}
r e t u r n nb
E lem == 0 ? 0 : moy / nb
E lem ;
}
V. Granet U.N.S.A.
Le langage Java
80
V. Granet U.N.S.A.
Le langage Java
81
Fichier dobjets
Fichier de texte
ObjectInputStream et ObjectOutputstream
Object readObject()
void writeObject(Object)
- caract`eres Unicode
- FileReader et FileWriter
os . writeObject ( r );
os . close ();
ObjectInputStream is = new ObjectInputStream (
new FileInputStream ( " Frect " ))
// lecture dun objet de type Rectangle sur le fichier is
interface Serializable
public
c l a s s Rectangle i m p l e m e n t s Serializable {
...
V. Granet U.N.S.A.
Le langage Java
82
V. Granet U.N.S.A.
Le langage Java
83
E/S bufferisees
FileReader is = new FileReader (" entr
e e " );
boolean
e tatDansMot = f a l s e ;
BufferedInputStream, BufferedOutputStream
nbCar ++;
BufferedReader, BufferedWriter
i f (c == || c == \ t || c == \ n ) {
// c est un s
eparateur de mot
i f (
e tatDansMot )
e tatDansMot = f a l s e ;
i f ( c == \ n )
nbLignes ++;
}
i f (!
e tatDansMot ) {
// 1er car du mot incr
ementer le compteur de mots
nbMots ++;
e tatDansMot = t r u e ;
}
}
// fin de fichier afficher les r
esultats
is . close ();
System . out . println ( nbLignes + " " + nbMots + " " + nbCar
V. Granet U.N.S.A.
Le langage Java
84
V. Granet U.N.S.A.
Le langage Java
85
LAPI
V. Granet U.N.S.A.
Le langage Java
86
V. Granet U.N.S.A.
Le langage Java
87
collections
arithmetique precision infinie
gestion dimages 2D et3D
gestion du son
interfaces graphiques et applet
processus legers - synchronisation
reseau (URL, mod`ele client-serveur RMI, objets
distribues IDL Corba)
beans
base de donnees (jdbc)
reflexivite
SDK (mecanismes de securite)
V. Granet U.N.S.A.
Le langage Java
Collections et Tables
88
paquetage java.util
Vector, tableaux dynamiques
Hashtable, tables dadressage dispers
e
Stack, piles
ensembles
listes
arbres
algorithmes de tri
algorithmes de recherche
...
V. Granet U.N.S.A.
Le langage Java
89
Collections
La classe
Collection
List
Vector
Set
Vector
LinkedList
SortedSet
HashSet
// 0
TreeSet
// 10
//
20
//
19
//
v . removeElementAt (0);
System . out . println ( v . size ());
List < String > vs = new Vector < String >();
v . removeAllElements ();
V. Granet U.N.S.A.
Le langage Java
90
V. Granet U.N.S.A.
Le langage Java
91
Tables
La classe
Hashtable
Map
SortedMap
ht . put ( " Paul " , 3);
TreeMap
HashMap
Hashtable
i f ( n != n u l l )
System . out . println ( " Pierre = " + n );
Valeur + Cle
V. Granet U.N.S.A.
Le langage Java
92
V. Granet U.N.S.A.
Le langage Java
93
Les Properties
Threads
sous-classe de Hashtable
correspondance cles et des valeurs String
une instance de Properties peut etre reliee `a
une autre instance de Properties
lues et sauvegardees dans un fichier (texte ou
XML)
c l a s s MonThread e x t e n d s Thread {
p u b l i c MonThread () { ... }
p u b l i c v o i d run () { ... }
public
c l a s s TestThread {
public
static
System . out . println ( p2 . getProperty ( " Acteur " ," inconnu " ));
propri
et
es de lenvironnement dex
ecution
System . out . print ( System . getProperty (" java . version " ));
}
V. Granet U.N.S.A.
Le langage Java
94
V. Granet U.N.S.A.
Le langage Java
95
Interfaces Graphiques
Introspection
V. Granet U.N.S.A.
Le langage Java
96
V. Granet U.N.S.A.
Le langage Java
97
Introspection
possibilite de consulter et dutiliser
dynamiquement la structure de classe des
objets.
necessaire pour les butineurs de classes,
debogueurs, ...
la classe Class et le paquetage
java.lang.reflect permet lintrospection
Beans
V. Granet U.N.S.A.
Le langage Java
98
V. Granet U.N.S.A.
Le langage Java
99
Beans (1/13)
Beans (2/13)
V. Granet U.N.S.A.
Le langage Java
Un bean :
est capable dintrospection (reflect, inspector)
poss`ede des proprietes (accessibles par des
methodes setXX(), getXX(), isXX()),
realise la persitence (une fois crees, les beans
doivent pouvoir etre conserves)
communication entre beans par des evenements
100
V. Granet U.N.S.A.
Le langage Java
101
Beans (3/13)
Beans (4/13)
Compilation et archivage
javac
i m p o r t java . io .*;
public
FirstBean.java
c l a s s FirstBean e x t e n d s Canvas
i m p l e m e n t s Serializable {
final
public
static
i n t RECTANGLE = 0;
final
public
static
i n t CERCLE = 1;
protected
fichier manifest
p u b l i c FirstBean () {
Java-Bean: True
p u b l i c i n t getForme () { r e t u r n forme ; }
p u b l i c v o i d setForme ( i n t f) { forme = f; }
}
V. Granet U.N.S.A.
Le langage Java
102
V. Granet U.N.S.A.
Le langage Java
103
Beans (5/13)
Beans (6/13)
c l a s s MyEvent e x t e n d s EventObject {
p u b l i c MyEvent ( Object o ) {
s u p e r ( o );
}
}
i n t e r f a c e MyEventListener e x t e n d s EventListe
p u b l i c a b s t r a c t v o i d myEventPerformed ( MyEvent e
}
V. Granet U.N.S.A.
Le langage Java
104
V. Granet U.N.S.A.
Le langage Java
105
Beans (7/13)
i m p o r t java . util .*;
public
c l a s s Source {
p u b l i c s y n c h r o n i z e d v o i d addMyEventListener ( MyEv
myEventListeners . addElement ( l );
public
c l a s s Cible i m p l e m e n t s MyEventListener {
p u b l i c s y n c h r o n i z e d v o i d removeMyEventListener ( M
p u b l i c Cible () {
myEventListeners . removeElement ( l );
src . addMyEventListener ( t h i s );
}
}
p r o t e c t e d v o i d notifyMyEvent () {
p u b l i c v o i d myEventPerformed ( MyEvent e ) {
Vector l ;
MyEvent e = new MyEvent ( t h i s );
// callback ...
synchronized ( t h i s ) {
}
// pour
eviter toute modification
V. Granet U.N.S.A.
Le langage Java
106
V. Granet U.N.S.A.
Le langage Java
107
Beans (8/13)
Beans (9/13)
c l a s s FirstBean e x t e n d s Canvas i m p l e m e n t s
....
p r i v a t e PropertyChangeSupport changes
= new PropertyChangeSupport ( t h i s )
p u b l i c v o i d addPropertyListener ( PropertyChangeListene
{
changes . addPropertyChangeLi ste ner ( l );
}
p u b l i c v o i d removePropertyListener (
PropertyChangeListener l ) {
changes . removePropertyCha ng eLi st ene r (l );
getSource()
getOldValue()
getNewValue()
getPropertyName()
}
p u b l i c v o i d setForme ( i n t newForme )
{
i n t oldForme = newForme ;
forme = newForme ;
V. Granet U.N.S.A.
Le langage Java
108
V. Granet U.N.S.A.
109
Beans (10/13)
Beans (11/13)
Le langage Java
c l a s s BeanAudit
i m p l e m e n t s PropertyChangeListener ,
Serializable
{
......
p u b l i c v o i d propertyChange ( PropertyChangeEvent e )
....
}
...
}
V. Granet U.N.S.A.
Le langage Java
110
V. Granet U.N.S.A.
Le langage Java
111
Beans (12/13)
Beans (13/13)
Le bean qui emet le veto
c l a s s FirstBean e x t e n d s Canvas
public
i m p l e m e n t s Serializable {
c l a s s BeanAudit
i m p l e m e n t s VetoableChangeListener ,
p r i v a t e VetoableChangeSupport v
e to
Serializable
= new VetoableChangeSupport ( t h i s )
......
p u b l i c v o i d addVetoableChangeLis ten er (
p u b l i c v o i d vetoableChange ( PropertyChangeEvent e )
VetoableChangeListener l ) {
t h r o w s PropertyVetoException {
....
PropertyChangeListener l ) {
changes . removeVetoableCha ng eLi st ene r (l );
}
p u b l i c v o i d setForme ( i n t newForme )
t h r o w s PropertyVetoException {
i n t oldForme = newForme ;
v
e to . fireVetoableChange (" forme " , oldForme , newForme );
forme = newForme ;
changes . firePropertyChange ( " forme " , oldForme , newForm
}
...
}
V. Granet U.N.S.A.
Le langage Java
112
V. Granet U.N.S.A.
Le langage Java
113
Introduction
c l a s s MonThread e x t e n d s Thread {
p u b l i c MonThread () { ... }
p u b l i c v o i d run () { ... }
Threads
}
public
c l a s s TestThread {
public
static
V. Granet U.N.S.A.
Le langage Java
114
V. Granet U.N.S.A.
Le langage Java
115
public
c l a s s Al
e atoire i m p l e m e n t s Runnable {
public
c l a s s TestProd {
public
static
new Al
e atoire (10 , 1). proc . start ();
p u b l i c v o i d run () {
new Al
e atoire (15 , 3). proc . start ();
while ( true ) {
new Al
e atoire (13 , 3). proc . start ();
c a t c h ( InterruptedException e ) {}
System . out . print ( rand . nextInt () + " " );
V. Granet U.N.S.A.
Le langage Java
116
V. Granet U.N.S.A.
Le langage Java
117
Etats
dun threads
BLOCKED
NEW
RUNNABLE
thread ex
ecutable, pr
et `
a disposer de la
puissance de calcul.
methode interrupt()
le processus peut verifier sil est interrompu ou
non (il g`ere linterruption)
p u b l i c v o i d run () {
TERMINATED
TIMED WAITING
thread en attente.
WAITING
c a t c h ( InterruptedException e ) {
// interruption lors du sleep
break ;
}
new Thread()
NEW
TERMINATED
yield()
start()
fin de run()
RUNNABLE
sleep(dure)
fin dure
TIMED_WAITING
V. Granet U.N.S.A.
IO?
IO ok
BLOCKED
Le langage Java
wait()
notify()
WAITING
118
V. Granet U.N.S.A.
Le langage Java
119
public
c l a s s TestProd {
public
static
new Al
e atoire (10 , 1). proc . start ();
public
new Al
e atoire (15 , 3). proc . start ();
static
Al
e atoire p1 = new Al
e atoire (10 , 1);
Al
e atoire p = new Al
e atoire (13 , 1);
p . proc . start ();
Al
e atoire p2 = new Al
e atoire (15 , 2);
...
Al
e atoire p3 = new Al
e atoire (13 , 1);
// arr^
et du 3`
eme thread
try {
p1 . proc . join (); // attendre la fin de p1
p2 . proc . join (); // attendre la fin de p2
p3 . proc . join (); // attendre la fin de p3
}
c a t c h ( InterruptedException e ) {}
V. Granet U.N.S.A.
Le langage Java
...
}
120
V. Granet U.N.S.A.
static void
String
currentThread()
void
Retourne une r
ef
erence sur le thread
actif.
void
join(long millis)
ou
join(long
getName()
void
notify()
R
eveille le thread pr
ec
edemment mis en attente.
getPriority()
void
getState()
run()
Cette m
ethode par d
efaut ne fait rien. Si le
thread est issu dun objet de type Runnable,
cest la m
ethode run de cet objet qui est
ex
ecut
ee ou sinon sa red
efinition
eventuelle.
interrupted()
ou
Retourne l
etat courant du thread.
static boolean
join()
dumpStack()
Retourne la priorit
e du thread.
Thread.State
interrupt()
Interrompt le thread.
121
Le langage Java
isAlive()
setName(String name)
setPriority(int newPriority)
Change la priorit
e du thread.
V. Granet U.N.S.A.
Le langage Java
122
V. Granet U.N.S.A.
Le langage Java
123
start()
Provoque le d
emarrage du thread, la JVM appelle alors sa m
ethode run .
void
wait()
c l a s s CompteBancaire {
p r i v a t e d o u b l e solde ;
p u b l i c s y n c h r o n i z e d v o i d op
e ration ( d o u b l e som
yield()
V. Granet U.N.S.A.
Le langage Java
124
}
}
V. Granet U.N.S.A.
Le langage Java
125
...
s y n c h r o n i z e d (...) { // debut du bloc contr^ole
...
vo id uneM
ethode`
A S y n c h r o n i s e r () {
// r
eveil et reprise du cours de lex
ecution
synchronized ( t h i s ) {
...
...
V. Granet U.N.S.A.
Le langage Java
126
V. Granet U.N.S.A.
Le langage Java
127
File dattente
public
p u b l i c s y n c h r o n i z e d v o i d enfiler ( T e ) {
addElement ( e );
notify ();
Producteurs
Consommateurs
p u b l i c s y n c h r o n i z e d T d
e filer () {
w h i l e ( isEmpty ())
try {
wait ();
}
c a t c h ( InterruptedException e ) {
return nul l ;
}
T e = elementAt (0);
removeElementAt (0);
r e t u r n e;
}
} // fin classe File
V. Granet U.N.S.A.
Le langage Java
128
V. Granet U.N.S.A.
Le langage Java
129
Tubes (1/2)
Tubes (2/2)
PipedInputStream et PipedOutputStream
les tubes dentree et de sortie doivent etre
connectes :
`
a la creation, avec le constructeur
Thread1
Tube
PipedOutputStream po = n u l l ;
Tread2
try {
po = new PipedOutputStream ( pi );
}
c a t c h ( IOException e ) { System . err . println ( e ); }
La synchronisation Producteur/Consommateur
est geree par le support dexecution
V. Granet U.N.S.A.
Le langage Java
130
V. Granet U.N.S.A.
Le langage Java
131
Applet
applet = petite application graphique
necessite une autre application graphique
(navigateurs, appletviewer)
plugin (inclus dans la jre)
classe Applet
lang.Object
awt.Component
Applet
awt.Container
awt.Panel
applet.Applet
V. Granet U.N.S.A.
Le langage Java
132
V. Granet U.N.S.A.
Le langage Java
133
Exemple
AppletContext
Concept de contexte dexecution (document
HTML), information sur lenvironnement, et en
particulier sur les autres applets du document.
c l a s s HelloWorldApplet e x t e n d s Applet {
AppletContext Applet.getAppletContext()
Applet AppletContext.getApplet(String name)
Enumeration<Applet> AppletContext.getApplets()
void AppletContext.showStatus(String status)
void AppletContext.showDocument(URL url)
Font f ;
p u b l i c v o i d init () {
f = new Font ( " Times " , Font . BOLD , 20);
}
p u b l i c v o i d paint ( Graphics g ) {
g . setFont ( f );
g . setColor ( Color . pink );
g . drawString ( " Hello World ! " , 5 , 25);
}
} // fin classe HelloWorldApplet
<OBJECT code="HelloWorldApplet.class"
width=400 height=150>
</OBJECT>
V. Granet U.N.S.A.
Le langage Java
134
V. Granet U.N.S.A.
Le langage Java
135
AudioClip
V. Granet U.N.S.A.
Le langage Java
136
V. Granet U.N.S.A.
Le langage Java
137
enements
Ev
Chargement de fichiers
images ou sons, relatifs `a une URL (base du code
ou base du document)
....
return true ;
}
V. Granet U.N.S.A.
Le langage Java
138
V. Granet U.N.S.A.
Le langage Java
139
Composants Graphiques
c l a s s BoutonURL e x t e n d s Applet
i m p l e m e n t s ActionListener {
Button b ;
String url ;
p u b l i c v o i d init () {
url = getParameter ( " URL " );
V. Granet U.N.S.A.
Le langage Java
140
V. Granet U.N.S.A.
Le langage Java
141
// Param`
etre
Type
Description
" page `
a afficher " } ,
};
r e t u r n info ;
V. Granet U.N.S.A.
Le langage Java
142
V. Granet U.N.S.A.
Le langage Java
143
Securite
System . getProperty ( " " os . name " ); // OK
V. Granet U.N.S.A.
Le langage Java
144
V. Granet U.N.S.A.
Le langage Java
145
Thread et Applet
p u b l i c v o i d stop () {
i f ( proc != n u l l ) {
c l a s s ThreadApplet
repaint ();
e x t e n d s Applet i m p l e m e n t s Runnable {
p r i v a t e Thread proc ;
}
}
p u b l i c v o i d paint ( Graphics g ) {
p u b l i c v o i d init () {
// redessiner le motif
p u b l i c v o i d start () {
i f ( proc == n u l l ) {
proc = new Thread ( t h i s );
proc . start ();
}
}
V. Granet U.N.S.A.
Le langage Java
146
V. Granet U.N.S.A.
Le langage Java
147
Introduction
Pb reduction des clignotements lies au reaffichage
1. ne pas effacer la fenetre ;
2. redessinner le strict necessaire (detourage) ;
3. le double buffering.
Animation
V. Granet U.N.S.A.
Le langage Java
148
V. Granet U.N.S.A.
Le langage Java
149
2 - Detourage
Ne reafficher que ce qui est necessaire
p u b l i c v o i d update ( Graphics g ) {
g. setColor ( getBackground ());
g. fillRect (0 , 0 , getsize (). width , getsize (). height );
setClip(x, y, w, h) et clipRect(x, y, w, h)
p u b l i c v o i d update ( Graphics g ) {
// proc
edure "paint" ait effectivement
et
e ex
ecut
ee.
paint ( g );
paintOK = f a l s e ;
repaint ();
w h i l e (! paintOK ) {
t r y { .... sleep ( time ); }
c a t c h ( InterruptedException e ) {}
}
V. Granet U.N.S.A.
Le langage Java
} // fin repeindre
150
V. Granet U.N.S.A.
Le langage Java
151
Image
temp ;
g . drawImage ( temp , 0 , 0 , t h i s );
Graphics gTemp ;
g est connecte `
a lecran reel, temp est limage `a
dessiner a` partir des coordonnees (0,0). Le dernier
param`etre supervise laffichage.
dans init :
temp
// suppression du clignotement
p u b l i c v o i d update ( Graphics g ) {
V. Granet U.N.S.A.
Le langage Java
152
V. Granet U.N.S.A.
Le langage Java
153
Part 17: R
eseau
URL(adr)
URL(prot,host,file)
R
eseau
getProtocol()
getHost()
getFile()
URLConnection openConnection()
setDoInput(), setDoOutput()
connect()
openStream() (pour la lecture)
getContent()
V. Granet U.N.S.A.
Le langage Java
154
V. Granet U.N.S.A.
Le langage Java
155
Part 17: R
eseau
Part 17: R
eseau
URL u =
new URL ( " ftp :// vg : secret@taloa . unice . fr / in / f" );
i m p o r t java . io .*;
public
c l a s s AfficherUrl {
public
// indiquer lacc`
es en
ecriture
uc . setDoOutput ( t r u e );
static
try {
// cr
eer un flot de sortie
i n t c;
i n t b;
os . write (( b y t e ) b );
// fin de fichier
c a t c h ( MalformedURLException e ) {
System . err . println (" Bad Url : " +
}
c a t c h ( UnknownHostException e ) {
System . err . println (" Bad Url : " +
}
}
} // fin classe AfficherUrl
V. Granet U.N.S.A.
Le langage Java
156
Part 17: R
eseau
V. Granet U.N.S.A.
Le langage Java
157
Part 17: R
eseau
Socket
Modes de transmission
Ordinateur B
programme
programme
2) Mode connecte :
circuit virtuel de commutation etabli au
prealable
Internet TCP
connexion fiable, ordre garanti
socket
port
port
Internet
Le langage Java
158
V. Granet U.N.S.A.
Le langage Java
159
Part 17: R
eseau
Part 17: R
eseau
c l a s s Emetteur {
public
InetAddress adrSource = InetAddress.getLocalHost();
static
t h r o w s IOException {
// adresse du destinataire
// cr
eation de la socket
DatagramPacket paquet =
adrDest , portDes
socket . send ( paquet );
}
}
}
V. Granet U.N.S.A.
Le langage Java
160
Part 17: R
eseau
V. Granet U.N.S.A.
Le langage Java
161
Part 17: R
eseau
c l a s s Receveur {
public
DatagramPacket paquet =
static
// cr
eation de la socket
// cr
eer un paquet de r
eception des messages
// afficher le message re
cu
V. Granet U.N.S.A.
Le langage Java
162
V. Granet U.N.S.A.
Le langage Java
163
Part 17: R
eseau
Part 17: R
eseau
Datagrammes
Datagrammes - Multicast
Receveur.java
djinn $ java
Receveur 17000
V. Granet U.N.S.A.
Le langage Java
164
Part 17: R
eseau
V. Granet U.N.S.A.
Le langage Java
165
Part 17: R
eseau
c l a s s Emetteur {
public
// ou bien
t h r o w s IOException {
static
// creation du socket
while ( true ) {
System . out . print (" > " );
String msg = StdInput . readLine ();
i f ( msg == n u l l ) b r e a k ;
//
ecrire le message
V. Granet U.N.S.A.
Le langage Java
166
V. Granet U.N.S.A.
Le langage Java
167
Part 17: R
eseau
Part 17: R
eseau
c l a s s Receveur {
public
static
t h r o w s IOException {
i n t port = Integer . parseInt ( args [0]);
// cr
eation de la socket serveur
BufferedReader din =
new BufferedReader (
V. Granet U.N.S.A.
Le langage Java
168
Part 17: R
eseau
V. Granet U.N.S.A.
Le langage Java
169
Part 17: R
eseau
while ( true ) {
// attendre la prochaine connexion
djinn $ javac
Receveur.java
djinn $ java
Receveur 17000
V. Granet U.N.S.A.
Le langage Java
170
V. Granet U.N.S.A.
Le langage Java
171
Part 17: R
eseau
Part 17: R
eseau
c l a s s GestionDuClient i m p l e m e n t s Runnable {
i m p o r t java . io .*;
public
p r i v a t e Socket socket ;
c l a s s Serveur {
public
static
p r i v a t e BufferedReader din ;
t h r o w s IOException {
socket = s ;
while ( true ) {
p u b l i c v o i d run () {
while ( true )
try {
// cr
eer un paquet de r
eception des messages
+ " connect
e " );
// g
erer le client dans un thread
}
}
c a t c h ( IOException e) { b r e a k ; }
V. Granet U.N.S.A.
Le langage Java
172
Part 17: R
eseau
V. Granet U.N.S.A.
Le langage Java
173
Part 17: R
eseau
djinn $ javac
Serveur.java
djinn $ java
Serveur 17000
lyre.esinsa.unice.fr connect
e
lyre $ java
> abracadabra
>
V. Granet U.N.S.A.
Le langage Java
174
V. Granet U.N.S.A.
Le langage Java
175
Jni (1/6)
Jni (Java Native Interface) permet dexecuter du
code C, C++, ... dans une application Java
Interet :
reutilisation de code existant (biblioth`eque)
code particulier en assembleur
...
Jni permet une communication bidirectionnelle
entre entre les deux formes de code (Java et C par
exemple).
Jni
V. Granet U.N.S.A.
Le langage Java
176
V. Granet U.N.S.A.
Le langage Java
177
Jni (2/6)
Jni (3/6)
c l a s s HelloWorld {
p u b l i c n a t i v e v o i d displayHelloWorld ();
static {
// le code C est dans la biblioth`
eque hello
}
public
static
Java_HelloWorld_displayHelloWorld
}
}
On compile
javac HelloWorld.java
V. Granet U.N.S.A.
Le langage Java
178
V. Granet U.N.S.A.
Le langage Java
179
Jni (4/6)
Jni (5/6)
Le fichier C :
#i f n d e f _Included_HelloWorld
#d e f i n e _Included_HelloWorld
JNIEXPORT v o i d JNICALL
#i f d e f __cplusplus
e x t e r n " C" {
#e n d i f
/*
return ;
* Class :
HelloWorld
* Method :
displayHelloW or ld
* Signature : () V
*/
#e n d i f
#e n d i f
V. Granet U.N.S.A.
Le langage Java
180
V. Granet U.N.S.A.
Le langage Java
181
Jni (6/6)
Jni permet egalement lacc`es `a Java depuis le
code natif (C, C++).
Linterface JNI offre :
des definitions dequivalence de type (jboolean,
jint, jdouble, jstring, jarray, jclass, etc.)
des fonctions de manipulation de ces types par
lintermediaire de (JNIEnv *env)
lacc`es aux attributs et aux methodes dobjets
Java
V. Granet U.N.S.A.
Le langage Java
Jdk 1.5
182
V. Granet U.N.S.A.
Le langage Java
183
Nouveautes Tiger
Autoboxing
Autoboxing
Importation static
Enonc
e foreach
Enum
erations
Genericite
Character c = a ;
i n t i = new Integer (10);
Hashtable ht = new Hashtable ();
ht . put ( " Paul " , 3);
ht . put ( " Pierre " , 19);
Integer n = ( Integer ) ht . get (" Pierre " );
i f ( n != n u l l )
System . out . println (" Pierre = " + n );
V. Granet U.N.S.A.
Le langage Java
184
V. Granet U.N.S.A.
Le langage Java
185
Importation static
Enonc
e
foreach
(1/2)
i n t [] tab ;
....
on pourra ecrire :
i n t somme = 0;
f o r ( i n t i =0; i < tab . length ; i ++)
somme += tab [i ];
i n t [] tab ;
....
i n t somme = 0;
f o r ( i n t x : tab )
somme += x ;
V. Granet U.N.S.A.
Le langage Java
186
V. Granet U.N.S.A.
Le langage Java
187
Enonc
e
foreach
Enum
eration (1/2)
(2/2)
Enum
eration de constantes representees par des
noms (comme en C)
i f ( x % 2 == 0) somPairs += x ;
}
c l a s s Carte {
Couleur couleur ;
Valeur valeur ;
Carte ( Valeur v , Couleur c ) {
valeur = v ;
Vector v = new Vector ();
couleur = c ;
i n t somPairs = 0;
f o r ( Object x : v )
i f (( Integer ) x % 2 == 0) somPairs += ( Integer ) x ;
...
new Carte ( Valeur . as , Couleur . coeur );
...
V. Granet U.N.S.A.
Le langage Java
188
V. Granet U.N.S.A.
Le langage Java
189
Enum
eration (2/2)
enum Valeur {
deux (2) , trois (3) , quatre (4) , cinq (5) ,
} // fin enum
V. Granet U.N.S.A.
Le langage Java
190
V. Granet U.N.S.A.
Le langage Java
191
Genericite (1/5)
Genericite (2/5)
Object
}
c l a s s Pile <E > {
v o i d empiler ( E x ) {
// ajouter en t^
ete l
el
ement x
p . suivant = sommet ;
i f ( n != n u l l )
sommet = p ;
}
E sommet () {
r e t u r n sommet . val ;
v . addElement ( " toto " ); // ! erreur compilation
}
}
i f (x % 2 == 0) somPairs += x ;
V. Granet U.N.S.A.
Le langage Java
192
V. Granet U.N.S.A.
Le langage Java
193
Genericite (3/5)
Genericite (4/5)
// D
efinition simplifi
ee dune Pile g
en
erique
private
final
i n t N = 100;
private
i n t sommet = 0;
// pas de g
en
ericit
e sur les tableaux !
p r i v a t e T []
e l
e ments = ( T []) new Object [ N ];
p u b l i c v o i d empiler ( T x ) {
e l
e ments [ sommet ++] = x ;
p u b l i c v o i d d
e piler () {
p.empiler("bonjour");
sommet - -;
}
p.empiler(6); // OK
p u b l i c T sommet () {
return
e l
e ments [ sommet -1];
}
}
V. Granet U.N.S.A.
Le langage Java
194
V. Granet U.N.S.A.
Le langage Java
195
Genericite (5/5)
De meme :
et avec les interfaces :
v o i d afficherSommet ( Pile < Object > p ) {
System . out . println ( p. sommet ());
i n t e r f a c e Pile <T > { v o i d empiler ( T x );
...
Pile < Integer > p = new Pile < Integer >();
// Impl
ementation dune pile par un tableau
c l a s s PileCha^
n
e e <E > i m p l e m e n t s Pile <E > { ... }
...
Pile < String > p = new PileCha^
n
e e < String >();
Le langage Java
196
V. Granet U.N.S.A.
Le langage Java
197
Methodes generiques
...
afficherSommet ( pi ); // OK
Pile < String > ps = new Pile < String >();
afficherSommet ( ps ); // OK
V. Granet U.N.S.A.
Le langage Java
198
V. Granet U.N.S.A.
Le langage Java
199
JDBC (1/8)
Java Database Connectivity
offre la connexion dapplications Java avec
differents types de BD (SQL, tableurs, etc.)
API JDBC est independante du SGBD.
Ensemble de classes (java.sql.*)
client
client
Jdbc
midleware
serveur BD
Modele 2 couches
V. Granet U.N.S.A.
Le langage Java
200
V. Granet U.N.S.A.
serveur BD
Modele 3 couches
Le langage Java
201
JDBC (2/8)
JDBC (3/8)
import java.sql.*
JDBC g`ere :
la connexion `a la BD
lenvoi de requetes SQL
lexploitation des resultats provenant de la
BD
V. Granet U.N.S.A.
Le langage Java
202
V. Granet U.N.S.A.
Le langage Java
203
DriverManager :
try {
// cr
eer une nouvelle instance du Driver
Class . forName (" com . mysql . jdbc . Driver " ). newInstance ();
} c a t c h ( Exception ex ) { /* ge rer les erreurs */ }
// cr
eer un Statement
Connection conn = n u l l ;
try {
String urlBD = " jdbc : mysql :// djinn . polytech . unice . fr / bd " ;
conn = DriverManager . getConnection ( urlBD , " vg " ," pass " );
// code de lapplication qui acc`
ede `
a la BD
...
} c a t c h ( Exception ex ) { /* ge rer les erreurs */ }
finally {
V. Granet U.N.S.A.
Le langage Java
204
V. Granet U.N.S.A.
Le langage Java
205
PreparedStatement pstmt =
conn . prepareStatement (
" INSERT INTO animal VALUES (? ,? ,? ,? ,? , NULL ); " );
// d
efinir les param`
etres
rs . absolute (2);
pstmt . setString (1 , " Coco " );
w h i l e ( rs . next ()) {
V. Granet U.N.S.A.
Le langage Java
206
V. Granet U.N.S.A.
Le langage Java
207
CallableStatement cstmt =
conn . prepareCall ( " call myfunc (? ,?); " );
// fixer la valeur du 1er param`
etre donn
ee ( e.g. un r
eel)
V. Granet U.N.S.A.
Le langage Java
208