Caracteristicas Java SE 5.0

Anuncio
Características Java SE 5.0
Integración de Sistemas
Facultade de Informática
Universidade da Coruña
2006-07
Java SE 5.0 (I)
„
Generics
„
„
„
Bucle for
„
„
Facilidad en iteraciones sobre arrays y colecciones.
Autoboxing/Unboxing
„
„
Mejora en el sistema de tipos.
Añade comprobación de tipos en tiempo de compilación para
el framework de collections y elimina los castings.
Elimina la conversión manual entre tipos primitivos (int) y
los tipos envoltorio correspondientes (Integer).
Typesafe Enums
„
Tipos enumerados orientados a objetos.
2
Java SE 5.0 (II)
„
Varargs
„
„
Static Import
„
„
Métodos con número de argumentos variable.
Acceso no calificado a miembros estáticos de un tipo sin
heredar de él.
Annotations
„
„
Posibilidad de anotar el código fuente.
Posibilita que herramientas generen código a partir de las
anotaciones.
3
Generics (I)
„
Su uso principal es sobre el framework de
Collections, aunque también tiene otros muchos
usos.
„
„
Cuando se recupera un elemento de una colección es
necesario hacer un cast.
„
„
Similar a los Templates de C++.
El compilador no comprueba el cast. Puede fallar en tiempo
de ejecución.
Generics proporciona un mecanismo para indicar el
tipo de una colección al compilador.
„
„
Puede ser comprobado en tiempo de compilación.
El compilador puede insertar los cast cuando se recuperan
los elementos.
4
Generics (II)
// Removes the 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
if (((String) i.next()).length() == 4) {
i.remove();
}
}
}
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); ) {
if (i.next().length() == 4) {
i.remove();
}
}
}
„
„
<Type> se lee como “de tipo”
Si el compilador compila sin warnings nunca se lanzará
ClassCastException.
5
Generics (III)
„
Información de tipos sólo presente en tiempo de
compilación.
„
„
„
Interoperabilidad con código heredado.
Los casts generados pueden fallar en tiempo de ejecución al
interoperar con código heredado.
java.util.Collections Î Clases envoltorio “comprobadas”.
Garantizan comprobación de tipos en tiempo de ejecución
(al insertar un elemento de un tipo no correcto lanzaría
ClassCastException).
Set<String> s =
Collections.checkedSet(new HashSet<String>(), String.class);
6
Bucle For-Each
„
„
“:” se lee como “en”
Aplicable a colecciones y arrays
void cancelAll(Collection<TimerTask> c) {
for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); ) {
i.next().cancel();
}
}
void cancelAll(Collection<TimerTask> c) {
for (TimerTask t : c) {
t.cancel();
}
}
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a) {
result += i;
}
return result;
}
7
Autoboxing / Unboxing (I)
„
No es posible insertar tipos primitivos en colecciones.
„
„
„
Boxing: Para insertar se usa el tipo envoltorio adecuado (int
Î Integer).
Unboxing: Al recuperarlo se convierte de nuevo al tipo
primitivo (Integer Î int).
Autoboxing / unboxing automatiza este proceso.
import java.util.*;
// Prints a frequency table of the words on the command line
public class Frequency {
public static void main(String[] args) {
Map<String, Integer> m = new TreeMap<String, Integer>();
for (String word : args) {
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq + 1));
}
System.out.println(m);
}
}
java Frequency if it is to be it is up to me to do the watusi
{be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}
8
Autoboxing / Unboxing (II)
// List adapter for primitive int array
public static List<Integer> asList(final int[] a) {
return new AbstractList<Integer>() {
public Integer get(int i) {
return a[i];
}
// Throws NullPointerException if val == null
public Integer set(int i, Integer val) {
Integer oldVal = a[i];
a[i] = val;
return oldVal;
}
public int size() { return a.length; }
};
}
„
Si se intenta hacer un autounbox de un objeto con
valor null se lanza NullPointerException.
9
Enums (I)
„
Soporte para tipos enumerados.
enum Season { WINTER, SPRING, SUMMER, FALL }
„
La declaración enum define una clase a la que se
pueden añadir campos, métodos, hacer que
implemente interfaces, …
10
import java.util.*;
public class Card {
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank rank() { return rank; }
public Suit suit() { return suit; }
public String toString() { return rank + " of " + suit; }
private static final List<Card> protoDeck = new ArrayList<Card>();
// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
protoDeck.add(new Card(rank, suit));
}
public static ArrayList<Card> newDeck() {
return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}
}
11
Enums (III)
public enum
MERCURY
VENUS
EARTH
MARS
JUPITER
SATURN
URANUS
NEPTUNE
PLUTO
Planet {
(3.303e+23,
(4.869e+24,
(5.976e+24,
(6.421e+23,
(1.9e+27,
(5.688e+26,
(8.686e+25,
(1.024e+26,
(1.27e+22,
2.4397e6),
6.0518e6),
6.37814e6),
3.3972e6),
7.1492e7),
6.0268e7),
2.5559e7),
2.4746e7),
1.137e6);
private final double mass;
// in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass()
{ return mass; }
private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}
12
Enums (IV)
public static} void main(String[] args) {
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
public enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
// Do arithmetic op represented by this constant
double eval(double x, double y){
switch(this) {
case PLUS:
return x + y;
case MINUS: return x - y;
case TIMES: return x * y;
case DIVIDE: return x / y;
}
throw new AssertionError("Unknown op: " + this);
}
}
13
Varargs
„
Métodos que reciben un número variable de
argumentos.
„
„
Hacer que reciba un array y meter ahí los argumentos.
Varargs automatiza y oculta este proceso.
public static String format(String pattern, Object... arguments);
„
Los tres puntos indican que el argumento final (siempre
tiene que ser el último) puede ser pasado como un array o
como una secuencia de argumentos.
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet "
+ "{0,number,integer}.",
7, new Date(), "a disturbance in the Force");
„
Uso en APIs de reflection y formateo de mensajes, y
en la nueva característica printf.
14
Static Import
„
Para acceder a miembros estáticos es necesario
especificar el nombre de la clase que lo declara.
double r = Math.cos(Math.PI * theta);
„
“Constant Interface Antipattern “
„
„
Poner miembros estáticos en una interfaz y heredar de ella.
La construcción “static import” permite acceso no
calificado a miembros estáticos de un tipo sin
heredar de él.
import static java.lang.Math.PI;
import static java.lang.Math.*;
double r = cos(PI * theta);
15
Annotations (I)
„
„
La plataforma Java siempre ha poseído algunas anotaciones adhoc.
„ Modificador transient, etiqueta @deprecated.
Java 5: Anotaciones de propósito general ÎMetadatos.
„
„
Permite definir tus propias anotaciones.
Compuesto por:
„
„
„
„
„
„
„
„
Sintaxis para declarar tipos de anotaciones.
Sintaxis para anotar las declaraciones.
APIs para leer las anotaciones.
Una representación de un fichero de clase para anotaciones.
Una herramienta para procesar las anotaciones.
Las anotaciones no afectan a la semántica de los programas
directamente pero afectan a la manera en que son tratados por
herramientas y librerías.
Las anotaciones se pueden leer desde los ficheros fuente, ficheros
de clase o por reflection en tiempo de ejecución.
Una anotación es un tipo especial de modificador, por tanto puede
usarse en cualquier sitio donde puedan usarse éstos.
16
Annotations (II)
/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
*/
public @interface RequestForEnhancement {
int
id();
String synopsis();
String engineer() default "[unassigned]";
String date();
default "[unimplemented]";
}
@RequestForEnhancement(
id
= 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date
= "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
17
Referencias
„
Nuevas Características de Java SE 5.0
„
„
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
Java Programming Language, The, 4th Edition
„
„
Ken Arnold, James Gosling, David Holmes.
Addison Wesley Professional.
18
Descargar