Java7, cambios en la sintaxis del lenguaje

Anuncio
Java7, cambios en la sintaxis del lenguaje
Los dos mayores cambios en la sintaxis de Java son tratados a parte en sendos artículos:
•
Posibilidad de utilizar variables de tipo String en sentencias switch.
•
Manejo mejorado de recursos: try-with-resources.
El resto de cambios menores son:
Números en formato binario. Hasta ahora podíamos introducir valores en formato decimal y
en formato hexadecimal.
//An 8-bit 'byte' value:
byte aByte = (byte)0b00100001;
// A 16-bit 'short' value:
short aShort = (short)0b1010000101000101;
// Some 32-bit 'int' values:
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.
// A 64-bit 'long' value. Note the "L" suffix:
long aLong =
0b1010000101000101101000010100010110100001010001011010000101000101L;
Captura de múltiples excepciones. Hasta ahora cada bloque capturaba una excepción, por lo
que si queremos implementar el mismo código para tratar dos excepciones debíamos repetir
código:
catch (IOException ex) {
logger.debug(ex);
throw ex;
} catch (SQLException ex) {
logger.debug(ex);
throw ex;
}
Ahora podemos declarar más de una excepción en cada bloque, por lo que mejoramos la
legibilidad, reducimos líneas de código y sobre todo eliminamos duplicidades.
catch (IOException|SQLException ex) {
logger.debug(ex);
throw ex;
}
En este caso la variable ex es implícitamente final, es decir no podemos modificarla.
Relanzamiento de excepciones mejorado. Anteriormente si queríamos tratar dos excepciones
en el mismo bloque capturando por herencia, posteriormente no podíamos declarar en la
sentencia throws el tipo de las excepciones capturadas, sólo especificar el padre (que es la
clase utilizada en el bloque catch).
static class FirstException extends Exception { }
static class SecondException extends Exception { }
public void rethrowException(String exceptionName) throws Exception {
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (Exception e) {
throw e;
}
}
Ahora es posible especificar cada tipo en la declaración, a pesar de no ser utilizadas en el
bloque catch :
public void rethrowException(String exceptionName) throws
FirstException, SecondException {
try {
// ...
}
catch (Exception e) {
throw e;
}
}
Carácter subrayado en literales numéricos. Para facilitar la legibilidad del código, a partir de
esta versión se permite utilizar el carácter subrayado (“_”) para separar grupos de cifras en
literales numéricos.
long
long
long
long
creditCardNumber = 1234_5678_9012_3456L;
hexBytes = 0xFF_EC_DE_5E;
maxLong = 0x7fff_ffff_ffff_ffffL;
bytes = 0b11010010_01101001_10010100_10010010;
Más en detalle:
float pi1 = 3_.1415F;
// Invalid; cannot put underscores adjacent
to a decimal point
float pi2 = 3._1415F;
// Invalid; cannot put underscores adjacent
to a decimal point
long socialSecurityNumber1
= 999_99_9999_L;
// Invalid; cannot put underscores prior to
an L suffix
int x1 =
literal
int x2 =
int x3 =
end of a
int x4 =
_52;
// This is an identifier, not a numeric
5_2;
52_;
literal
5_______2;
// OK (decimal literal)
// Invalid; cannot put underscores at the
int x5 = 0_x52;
0x radix prefix
int x6 = 0x_52;
beginning of a number
int x7 = 0x5_2;
// OK (decimal literal)
// Invalid; cannot put underscores in the
// Invalid; cannot put underscores at the
// OK (hexadecimal literal)
int x8 = 0x52_;
end of a number
int
int
int
end
x9 = 0_52;
x10 = 05_2;
x11 = 052_;
of a number
// Invalid; cannot put underscores at the
// OK (octal literal)
// OK (octal literal)
// Invalid; cannot put underscores at the
Tipo de instanciación inferida. Anteriormente debemos explicitar en el constructor el tipo de
instanciación que deseamos:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
En la nueva versión Java7 no es necesario si el compilador puede inferir el tipo. Sería suficiente
con el operador <>
Map<String, List<String>> myMap = new HashMap<>();
En caso de no utilizar el operador <>, se generaría un aviso de conversión no chequeada
Map<String, List<String>> myMap = new HashMap(); // unchecked
conversion warning
Descargar