Download - Introduccion a J2SE 5
![Page 2: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/2.jpg)
CONTENIDO
● Introduccion J2SE 5● JSF● EJB
![Page 3: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/3.jpg)
PLANIFICACION
● SEMANA 1:– 11 Jul: Introducción a J2SE 1.5. Montaje del
entorno
– 12 Jul: Introduccion a JSF. Navegacion entre pantallas
– 13 Jul: Componentes estandar. Validaciones
– 14 Jul: Eventos
![Page 4: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/4.jpg)
PLANIFICACION
● SEMANA 2:– 18 Jul: Facelets
– 19 Jul: A4J
– 20 Jul: Richfaces
– 21 Jul: Introduccion a EJBs y cierre
![Page 5: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/5.jpg)
J2SE 5.0Novedades
![Page 6: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/6.jpg)
NOVEDADES J2SE 5.0
● Novedades en el lenguaje:– Varargs
– Bucle for-each
– Tipos genericos
– Tipos enumerados
– Autoboxing
– Anotaciones
![Page 7: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/7.jpg)
Varargs
● Declaracion en un metodo de un numero de argumentos indeterminado (variable).
● Similar en C / C++
![Page 8: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/8.jpg)
Varargs - declaracion
● Declaracion del metodo:
● Solo puede haber un unico argumento variable en la declaracion del metodo.
● El argumento variable tiene que ser el ultimo.
public void enviarEmail (String asunto, String... emails)
![Page 9: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/9.jpg)
Varargs - invocacion
● Invocacion:
● Se puede invocar sin dar valor al argumento variable:
enviarEmail ("Saludo","[email protected]","[email protected]");
enviarEmail ("Saludo");
![Page 10: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/10.jpg)
Varargs – acceso a argumentos
● Se accede como si fuera un array:
public void enviarEmail (String asunto,String... emails) {
for (int i = 0; i < emails.length; i++) {
... System.out.println ( emails[i] ); ...
}}
![Page 11: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/11.jpg)
For each
● Tambien llamado bucle “FOR mejorado”● Sintaxis sencilla para recorrer arrays o cualquier
implementacion del interfaz Iterable.● Forma de uso:
for ( tipoElementos elementoAuxiliar : estructuraElementos ) {
...
}
![Page 12: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/12.jpg)
For each - uso
● Antes:
● Ahora
for ( int i = 0; i < arrayStrings.length; i++ ) {
System.out.println( array[i] );
}
for ( String tmp : arrayStrings ) {
System.out.println( tmp );
}
![Page 13: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/13.jpg)
Tipos genericos
● Permite escribir interfaces o metodos sin definir los tipos de los argumentos o de las variables.
● Similar a los “templates” de C++.
![Page 14: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/14.jpg)
Tipos genericos¿por que los necesitamos?
● Definimos una clase Box que pueda almacenar cualquier tipo de objeto:
public class Box {
private Object object;
public void add(Object object) {this.object = object;
}
public Object get() {return object;
}}
![Page 15: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/15.jpg)
Tipos genericos¿por que los necesitamos?
● Utilizamos la clase anterior para almacenar un Integer:
● Hacemos un “casting” para recuperarlo
...
Box integerBox = new Box();
integerBox.add(new Integer(10));
...
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
...
![Page 16: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/16.jpg)
Tipos genericos¿por que los necesitamos?
● El compilador no sabe lo que metemos/recuperamos.
● El casting puede ser incorrecto! Y EL COMPILADOR NI SE DARA CUENTA!
...
Box integerBox = new Box();
integerBox.add(“10”));
...
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
...
![Page 17: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/17.jpg)
Tipos genericos¿por que los necesitamos?
![Page 18: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/18.jpg)
Tipos genericos¿por que los necesitamos?
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integerat BoxDemo1.main(BoxDemo1.java:9)
ERROR EN TIEMPO DE EJECUCION!!!
![Page 19: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/19.jpg)
Tipos genericos¿por que los necesitamos?
![Page 20: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/20.jpg)
Tipos genericos¿por que los necesitamos?
![Page 21: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/21.jpg)
Tipos genericos¿por que los necesitamos?
![Page 22: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/22.jpg)
Tipos genericosDeclaracion / Implementacion
● Misma clase, pero implementada con una variable de tipo generico:
public class Box<T> {
private T t;
public void add(T t) { this.t = t; }
public T get() { return t; }}
![Page 23: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/23.jpg)
Tipos genericos - Utilizacion
● Utilizamos la clase con la variable generica:
● No hay que hacer “casting”!!
...
Box<Integer> integerBox;integerBox = new Box<Integer>();
integerBox.add(new Integer(10));
...
Integer someInteger = integerBox.get();
System.out.println(someInteger);
...
![Page 24: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/24.jpg)
Tipos genericos - Utilizacion
● Si usamos un tipo incorrecto...
● Se produce un error EN TIEMPO DE COMPILACION
...
Box<Integer> integerBox;integerBox = new Box<Integer>();
integerBox.add(“10”);
...
Integer someInteger = integerBox.get();
System.out.println(someInteger);
...
![Page 25: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/25.jpg)
Tipos genericosDefinicion
● Podemos definir varios tipos genericos en la declaracion de clase.
● Los genericos asi definidos pueden ser usados para declarar variables en cualquier punto de la clase.
public class HashEntry<CLAVE, VALOR> {
private CLAVE clave;private VALOR valor;
public HashEntry(CLAVE clave, VALOR valor) {this.clave = clave;this.valor = valor;
}
... SETTERS/GETTERS ...
}
![Page 26: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/26.jpg)
Tipos genericosMetodos genericos
● Se llaman metodos genericos a aquellos que declaran un tipo generico como parametro
● El ambito del tipo generico definido como parametro es local, visible solo dentro del metodo!
public class Aleatorizador {
// Devuelve aleatoriamente uno de los dos objetospublic <T> T elegir(T x, T y) {
T elegido;
if ((Math.random()-0.5)>0) elegido = x;
else elegido = y;
return elegido;}
}
![Page 27: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/27.jpg)
Tipos genericosMetodos genericos
● Al invocar el metodo generico, no hace falta indicar el tipo. Java lo deduce de la clase del parametro
public class testAleatorizador {
public static void main(String[] args) {
Aleatorizador aleatorizador = new Aleatorizador();
String cadena = aleatorizador.elegir("Cadena 1", "Cadena 2");
System.out.println(cadena);
}
}
![Page 28: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/28.jpg)
Tipos genericosMetodos genericos
public class Box<T> {
private T t; public <U> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); }
public void add(T t) { this.t = t; }
public T get() { return t; }}
![Page 29: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/29.jpg)
Tipos genericosInterfaces
● Todo anterior se aplica a los interfaces
public class Cliente implements Guardable<File> {
public File salvar() {...
}
public boolean borrar(File copia) {return false;
}...
}
public interface Guardable<T> {
T salvar();boolean borrar(T copia);
}
![Page 30: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/30.jpg)
Tipos genericosBounding
● Se puede forzar que el tipo generico implemente un interfaz o extienda de una clase (bound)
● Extends sirve tanto para clases como interfaces
public class HashEntry <CLAVE extends Number, VALOR> {
private CLAVE clave;private VALOR valor;
public HashEntry(CLAVE clave, VALOR valor) {this.clave = clave;this.valor = valor;
}
...
}
![Page 31: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/31.jpg)
Tipos genericosBounding
● Un tipo que no cumpla el bounding, dara un error en tiempo de compilacion.
public class testHash {
public static void main(String[] args) {
HashEntry<Integer, String> hash = new HashEntry<Integer, String>(1,"uno");
HashEntry<String, String> hash = new HashEntry<String, String>("1","uno");
}}
![Page 32: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/32.jpg)
Tipos genericosBounding
Exception in thread "main" java.lang.Error:
Unresolved compilation problems: Bound mismatch:
The type String is not a valid substitute for the bounded parameter <CLAVE extends Number> of the type HashEntry <CLAVE,VALOR>
Error en tiempo de compilacion
![Page 33: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/33.jpg)
Tipos genericosBounding
● Mediante el simbolo “&” hacemos bounding de varios interfaces:
● Solo se puede hacer bounding a una unica clase.
public class HashEntry <CLAVE extends Number & Serializable, VALOR> {
...
}
![Page 34: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/34.jpg)
Tipos genericosComodines
● ¿Funcionara esto?
● Recordemos que Integer, Float, Double, Long, Short, etc derivan de Number
Box<Number> caja = new Box<Number>();
caja.add(new Integer(10));caja.add(new Double(10));
![Page 35: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/35.jpg)
![Page 36: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/36.jpg)
Tipos genericosComodines
● ¿Esto?
Box<Integer> caja = new Box<Number>();
![Page 37: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/37.jpg)
Tipos genericosComodines
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Type mismatch: cannot convert from Box<Number> to Box<Integer>
Error en tiempo de compilacion
![Page 38: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/38.jpg)
Tipos genericosComodines
● ¿Y funcionara esto?
Box<Number> caja = new Box<Integer>();
![Page 39: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/39.jpg)
Tipos genericosComodines
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Type mismatch: cannot convert from Box<Integer> to Box<Number>
TAMBIEN HAY ERROR EN TIEMPO DE COMPILACION!!!
![Page 40: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/40.jpg)
Tipos genericosComodines
● ¿Por que no funciona?
● Box<Integer> NO DERIVA de Box<Number> Son clases independientes.
● Tiene que haber alguna manera de hacerlo...
COMODINES!
![Page 41: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/41.jpg)
Tipos genericosComodines
● El simbolo ? es un comodin para sustituir cualquier tipo generico.
● Box<?> declara una variable capaz de almacenar una instancia de Box con cualquier tipo de dato generico.
Box<?> caja;
caja = new Box<Integer>();caja = new Box<Double>();caja = new Box<String>();
![Page 42: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/42.jpg)
Tipos genericosComodines
● Podemos hacer un bounding con el comodin y obligar a que el comodin derive de una clase o implemente un interfaz
● En el ejemplo, caja puede contener cualquier objeto de la clase Box con tipo Number o derivado.
Box<? extends Number> caja;
caja = new Box<Integer>();caja = new Box<Double>();
caja = new Box<String>(); //Error de compilacion
![Page 43: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/43.jpg)
Tipos genericosComodines
● En este otro ejemplo, caja puede contener cualquier objeto de la clase Box con tipo Integer o un padre de Integer.
Box<? super Integer> caja;
caja = new Box<Integer>();caja = new Box<Number>();
caja = new Box<Float>(); // Error de compilacion
![Page 44: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/44.jpg)
Tipos genericosLimitaciones
● Los tipos genericos solo existen en tiempo de compilacion, no en ejecucion.Una vez compilado el codigo, se traducen a tipos normales y no queda rastro de ellos en el “bytecode”.
![Page 45: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/45.jpg)
Tipos genericosLimitaciones
● Una limitacion importante del uso de genericos es que no se puede instanciar un tipo generico
public class Box<T> {
private T t;
public Box () { t = new T(); //Error! }
...
}
![Page 46: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/46.jpg)
Tipos genericosLimitaciones
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Cannot instantiate the type T
● No se puede instanciar un objeto de tipo generico puesto que el compilador no tiene ni idea de los constructores.
![Page 47: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/47.jpg)
Tipos genericosLimitaciones
● Truco (nada recomendable)
t = (T) t.getClass().newInstance();
![Page 48: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/48.jpg)
Tipos genericosLibrerías estandar
● A partir de la version 5 de Java, toda la librería (paquete) java.utils ha sido portada usando tipos genericos.
● Ejemplo:
ArrayList<Integer> lista = new ArrayList<Integer>();
![Page 49: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/49.jpg)
Tipos enumerados
● Nuevo tipo caracterizado por tener un numero limitado de valores posibles.
● Sustituyen (en ciertos casos) a las variables static final int.
![Page 50: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/50.jpg)
Tipos enumerados
● Declaracion:
● Uso:
public enum DiasSemana {
LUNES,MARTES,MIERCOLES,JUEVES,VIERNES,SABADO,DOMINGO
}
DiasSemana dia = DiasSemana.DOMINGO;
![Page 51: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/51.jpg)
Tipos enumerados
● Implementan el metodo equals()
● Tambien implementan el interfaz Comparable
DiasSemana dia = DiasSemana.VIERNES;
if (dia == DiasSemana.VIERNES) {System.out.println("Es viernes!");
}
if (dia.compareTo(DiasSemana.VIERNES) >=0) {System.out.println("Es fin de semana!");
}
![Page 52: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/52.jpg)
Tipos enumerados
● Y ordinal()...
● Y values()...
if (dia.ordinal() == 4) {System.out.println("Es el quinto dia de la semana!");
}
DiasSemana.values();
for (DiasSemana d : DiasSemana.values()) {System.out.println(d);
}
![Page 53: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/53.jpg)
Autoboxing● Ya no es necesario hacer el “boxing” o
“unboxing” entre primitivos y sus wrappers.● Antes:
● Ahora, con autoboxing:
Integer iObject= new Integer(1); // boxingint i= iObject.intValue(); // unboxing
Integer iObject= 1; // auto-boxingint i= iObject; // auto-unboxing
![Page 54: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/54.jpg)
Anotaciones
● Sintaxis que permite asociar informacion en forma de par atributo-valor a los diferentes elementos de programacion (paquetes, clases, metodos, atributos, variables...).
● No modifican la ejecucion del programa de por si. Simplemente añaden informacion que en tiempo de compilacion o ejecucion es extraida e interpretada por el compilador, herramientas o librerias.
![Page 55: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/55.jpg)
Anotaciones - Sintaxis
● Forma general
● Sin miembros (marcador)
● Con un unico miembro llamado value
@TipoAnotacion(nombre1=valor1,nombre2=valor2,...)
@TipoAnotacion
@TipoAnotacion(valor)
![Page 56: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/56.jpg)
Anotaciones - Sintaxis
● Con un miembro de tipo array
@TipoAnotacion(nombre={subvalor1,subvalor2,...},...)
![Page 57: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/57.jpg)
AnotacionesEjemplos: anotaciones estandar
● El compilador Java dispone de una serie de anotaciones estandar.
● Override:– Avisa al compilador de que el metodo “anotado”
sobrecarga el metodo de una superclase.
– El compilador avisara si no existe dicho metodo en la superclase.
@Override
public String toString() {...}
![Page 58: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/58.jpg)
AnotacionesEjemplos: anotaciones estandar
● Deprecated:– Avisa al compilador de que el elemento “anotado”
esta obsoleto.
– El compilador avisara si se usa un elemento obsoleto dentro de codigo no obsoleto
@Deprecatedpublic class Box {...}
@Deprecatedpublic int suma(int a, int b) {...}
![Page 59: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/59.jpg)
AnotacionesEjemplos: anotaciones estandar
● SuppressWarning:– Indica al compilador que warnings debe omitir.
– Se pasa un array de valores con los warnings omitidos (dependen del compilador): all, deprecation, checked, falltrough, path, serial, finally, unused...
@SuppressWarnings("unused")
public class test {
private int c;}
![Page 60: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/60.jpg)
Anotaciones - Definicion
● Tambien podemos definir nuestros propios tipos de anotaciones:
public @interface Registro {
String programador();int version();String fecha();
}
![Page 61: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/61.jpg)
Anotaciones - Definicion
● Una vez definida nuestra propia anotacion, podemos utilizarla:
@Registro(programador="ramiro", version=1, fecha="1 Marzo 2010")
public class Box {
...
}
![Page 62: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/62.jpg)
Anotaciones - Meta-anotaciones
● Una meta-anotacion es una anotacion que se aplica a la definicion de otra anotacion
● Sirven para indicar el comportamiento de las anotaciones.
● Existen unas cuantas meta-anotaciones predefinidas:
Documented, Inherited, Retention, Target
![Page 63: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/63.jpg)
Anotaciones - Meta-anotaciones
Retention:● Especifica la politica para mantener en memoria la
anotacion● Unico miembro value con los siguientes posibles
valores (Enum RetentionPolicy)– SOURCE: La anotacion solo esta en el codigo fuente. Se
descarta por el compilador.
– CLASS: La anotacion se almacena en el fichero de la clase, pero no es accesible en tiempo de ejecucion. Comportamiento por defecto
– RUNTIME: La anotacion se almacena en el fichero de clase y es accesible en tiempo de ejecucion.
![Page 64: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/64.jpg)
Anotaciones - Meta-anotacionesTarget:● Indica para que elementos es aplicable la
anotacion:● Unico miembro value con los siguientes posibles
valores (Enum ElementType):– TYPE: clase, interfaz o enum
– METHOD
– PARAMETER
– CONSTRUCTOR
– LOCAL_VARIABLE
– ANNOTATION_TYPE
– PACKAGE
![Page 65: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/65.jpg)
Anotaciones - Definicion
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.METHOD})
public @interface Registro {
String programador();int version();String fecha();
}
![Page 66: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/66.jpg)
Anotaciones - Extraccion
● Podemos acceder a las anotaciones en tiempo de ejecucion mediante la API reflection
![Page 67: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/67.jpg)
Anotaciones – Extraccionimport java.lang.annotation.Annotation;import java.lang.reflect.Method;
public class TestMiClase {
public static void main(String[] args) {
MiClase miClase = new MiClase();
Class clase = miClase.getClass();
Registro anotacion; Anotacion = (Registro)clase.getAnnotation(Registro.class);
System.out.println(anotacion);
System.out.println("REGISTRO - Programador: " + anotacion.programador() + " ; Version: " + anotacion.version());
for (Method metodo : clase.getMethods()) {for (Annotation anotacion2 : metodo.getAnnotations())
System.out.println("METODO: " + metodo.getName() + " - " + anotacion2);
}
}}
![Page 68: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/68.jpg)
Ejercicio 1● Implementar, utilizando los tipos genericos, una
pila de datos. Utilice internamente un arrayList para almacenar los elementos.
● El metodo toString debe imprimir ordenadamente todos los elementos almacenados. Utilizar un bucle for mejorado para ello.
● Implementar el interfaz Iterable para que pueda ser recorrida la pila usando un for-each.
● Cree un constructor con una lista indeterminada de parametros (de tipo generico). Dicha lista de parametros sera utilizada para inicializar la pila
![Page 69: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/69.jpg)
Ejercicio 2
● Implementar, utilizando los tipos genericos, una hash-table.
● La clave sera un tipo generico derivado de Number.
● El valor sera un tipo generico.● Se iran ordenado los datos por el valor de la clave
según se insertan en la hash-table
![Page 70: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/70.jpg)
Ejercicio 3
● Programar un DAO que sea capaz de gestionar cualquier tipo de objeto.
● Cada instancia de este DAO se particularizara para una clase concreta.
● En vez de utilizar una DB, almacenaremos los datos en una estructura de memoria dinamica (ej: HashMap)
DAOGenerico<usuario> usuarioDAO = new DAOGenerico<usuario>();
![Page 71: Introduccion a J2SE 5](https://reader033.vdocuments.co/reader033/viewer/2022051208/544be7e1b1af9fb60f8b4afa/html5/thumbnails/71.jpg)
Ejercicio 4
● Modifique el DAO del ejercicio 3 de modo que se pueda configurar su comportamiento mediante anotaciones.
● La anotacion @Limit indicara el numero maximo de elementos a almacenar.