JavaOne Notes: 1.5 Features Tips and Techniques
After a less than thrilling session on Jini attended an excellent quick overview presentation of Java 1.5 features by BEA engineers.
Foreach
� avoids needing to cache collection size pre-loop (scopes size var appropriately)
� no access to index or iterator (e.g. remove current element)
Annotations
� @SuppressWarnings�.suppresses compiler warning for a specific block (e.g. @SupperWarnings(�deprecation�) )
� 1.5 currently ignores SuppressWarnings (supported in Eclipse 3.1 and JDK 1.6)
� SuppressWarnings (all, deprecation, unchecked, fallthrough, etc)
� @Deprecated: can�t indicate why, not a javadoc�if you use also put in javadoc tag to give more info to callers
� @Override: indicates that a method should be overriding a superclass, if superclass method doesn�t exist (i.e. it changed) an error is emitted
� Annotations are usefull in frameworks
� Not a pre-processor�you can�t modify the code that is generated; by design from Sun
� Not a silver bullet; don�t use for things they aren�t intended for (e.g. @Property to create get/set methods�this becomes essentially a macro�makes hard to synchronized since you can�t edit the code)
Enumerations
� Type-safe (much better than public static final int!!! failures occur pre-runtime now)
� Should be able to drop in 1.5 enums wherever ints are used today
� EnumMap and EnumSet are optimized specifically for when you are using enums in maps and sets�
� Can statically import enums (useful in the case where you are using a private enums�you can import inner class statically to avoid having to prepend inner class name)
� Hidden static methods not in java.lang.Enum: values() returns all enum values (finally!); valueOf(String) to convert string rep
� Enums can have methods! Very useful�
Varargs
� Use sparingly!
� Cleans up code where you have multiple methods that take varing numbers of methods�
� NOTE: Backward compatibility issues for callers that import your binary jar; changing FORCES you to recompile all clients!!!
� There is a backward compatibility map from array[] argument methods to var arg methods
Covariant Returns
� Design pattern
� Hide implementation details from API users
� Avoids bad behaviors like downcasts to internal types
� Impl can return specific type (rather than interface) and clients can avoid casts
Generics
� Type inferencing on invocation
� Generics w/ no parameters are determined by compiler by looking at where invoked (if value is returned and assigned, type == assigned type)
� Type inferencing is not possible where no type info is available from context of being called
� Can�t determine inference where called as a return from a method w/o assignment under certain situations (e.g. return x ? genericObj.foo() : null )
� Can�t determine inference by being casted (e.g.
� Type CAN be passed explicitly in this case: return genericObj.
Generics: Beyond collections
� Class
public T newInstance()
� Comparable
public int compareTo(T o)
� Enum
public Class
Using lower bound wildcards
� Array typing is too lose; generic typing is too strict
� List
� List extends Number> : exact element type isn�t known, but you do know it is a *subtype* of number
� Why use extends �> : great for hiding implementation details
� private Set extends Customer> getCustomers(); // hides the fact that the class returns an internal CustomerImpl class
� Very important for interfaces to avoid exposing impl details; e.g. void removeNegatives(List extends Number> list)
Upper bound wildcards
� List super Number>
� NOTE: type safety can make code obscenely bloated
Unbounded wildcard
� List> : have no idea what the heck is passed in, other than it�s an object; equivalent to List extends Object>
If read-only access is needed, use Collections.unmodifiiableCollection() for immutable collections (wrapper from java.util.collections)
Constructing Generics
� Example: Pair to enable returning multiple objects from a method
� Before 1.5 Generics you had to explicitly create wrapper classes (e.g. return new FileInfo(name, size))
� Under 1.5: Return new Pair
� Can be used for additional compile time type safety
Generic Methods
� �Necessary� when parameterizing the return (e.g.
� Type info for generics is lost at compile time (erasure)
� Type Tokens:
public class ArrayExample
// T must have a no arg constructor!!! No way to enforce, failures
// will occur at runtime if someone
private Class
public ArrayExample(Class
this.clazz = class;
}
public T[] getArray(int size) {
return (T[])Array.newInstance(clazz, size);
}
}
Migration 1.4 -> 1.5
� Safe to add generics gradually (binary compatible�but can�t compile on pre-1.5; even safe for subclasses to NOT be recoded to use generics)
� Raw collections should be avoided as of 1.5
� Temporary use of Collection�s checked wrappers can help (e.g. checkedCollection() )