Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
New language features in JDK 1.5: Enum, Annotations, Generics, For, Auto(un)boxing, Var-args, Static Import Vladimir Mencl DISTRIBUTED SYSTEMS RESEARCH GROUP http://nenya.ms.mff.cuni.cz/ CHARLES UNIVERSITY IN PRAGUE Faculty of Mathematics and Physics JDK 1.5 new language features • Changes to language and class-file format Enumerated types Annotations • metadata Generic types • Similar to C++ templates • Language shortcuts (no JVM/bytecode requirements) Vladimír Mencl Enter event name Enhanced for loop Autoboxing/unboxing Var args Static import 2 Enums: Traditional Approach public static final int COLOR_BLUE = 0; public static final int COLOR_GREEN = 1; public static final int COLOR_RED = 2; • severe problems: type unsafe (int) no namespace • must prefix COLOR_ to avoid collisions constants compiled into clients – must recompile printed value non-informative – is just int Vladimír Mencl Enter event name 3 Enums: JDK 1.5 public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } • fully-fledged class inherits from public abstract class Enum implements Comparable, Serializable { can be forced to implement arbitrary interfaces • one instance per value in public static final self-typed fields protected constructor Vladimír Mencl Enter event name 4 Enums: Enum Class Methods • Class getDeclaringClass() • self-type[] values() • static self-typed valueOf(Class enumType, String name) • toString() returns “user-friendly” instance name • low-level methods: String name() name of this enum constant int ordinal() // zero based Vladimír Mencl Enter event name 5 Enums: Adding Data and Behavior public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), // constructor arguments private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } } Vladimír Mencl Enter event name 6 Enums: Constant Specific Methods • abstract method declared in type • concrete methods defined per-constant public enum Operation { PLUS MINUS TIMES DIVIDE { { { { double double double double eval(double eval(double eval(double eval(double x, x, x, x, double double double double y) y) y) y) { { { { return return return return x x x x + * / y; y; y; y; }}, }}, }}, }}; // Do arithmetic op represented by this constant abstract double eval(double x, double y); } Vladimír Mencl Enter event name 7 Enums: API Additions • java.util.EnumSet bit-vector implemented static EnumSet range(E from, E to) • java.util.EnumMap iterators operate in natural order claim: operates in constant time Vladimír Mencl Enter event name 8 Annotations • Metadata Ad-hoc mechanisms in past • transient, @deprecated • JDK 1.5 annotations no direct effect on running program used by tools and libraries • (and these can influence the running program) • Usage: “can replace” BeanInfo class, EJB deployment descriptor Vladimír Mencl Enter event name 9 Annotation facility • syntax for declaring annotation types annotating declarations • API for reading annotations • class-file representation • annotation processing tool (apt) usage: implement a visitor class... Vladimír Mencl Enter event name 10 Annotation syntax • (meta-)instance of annotation type • element types: primitive enum String Class annotation array of these • elements declared as methods “getter” method may have a default value • annotations are special modifiers ... public, static, final ,... Annotation Examples • Annotation type definition public @interface RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date(); default "[unimplemented]"; } • Annotated method @RequestForEnhancement( id = 2868724, synopsis = "Enable time-travel", engineer = "Mr. Peabody", date = "4/1/3007" ) public static void travelThroughTime(Date destination) { ... } Annotations: More • Marker annotation type public @interface Preliminary { } • May omit parentheses @Preliminary public class TimeTravel { ... } • Convention: a single element is named “value” public @interface Copyright { String value(); } then, element name may be omitted @Copyright("2002 Yoyodyne") public class OscillationOverthruster { ... } Vladimír Mencl Enter event name 13 Annotations: Reflection Example import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Test { } public class Foo { @Test public static void m1() { } public static void m2() { } @Test public static void m3() { ... import java.lang.reflect.*; public class RunTests { ... for (Method m : Class.forName(args[0]).getMethods()) { if (m.isAnnotationPresent(Test.class)) { try { m.invoke(null); ... Annotation API • package java.lang.annotation interface Annotation • method: Class annotationType() reflection: java.lang.Class • isAnnotation() - if this Class represents an annotation type • boolean isAnnotationPresent(Class annotationClass) • Annotation getAnnotation(Class annotationClass) Meta-Annotations • annotation types can have annotations => meta annotations • predefined types Retention • RetentionPolicy() value SOURCE – discarded by compiler CLASS – store in class file but not in JVM • (default) RUNTIME – retain also in JVM ... Meta-Annotations (cont.) • Inherited • Documented • Target ElementType[] value() ElementType: • ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE (includes annotation type) • Example: @Documented @Retention(value=RUNTIME) @Target(value=ANNOTATION_TYPE) public @interface Retention {RetentionPolicy value(); ... } Vladimír Mencl Enter event name 17 Annotations: Example import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @interface Author { String value(); } @Author(“Vlada") public class MyClass { public static void main(String[] args) { Class cl = MyClass.class; Author author = (Author)cl.getAnnotation(Author.class); System.out.println(author.value()); } } Generics • abstraction over types • types may have a parameter • motivation: existing code is cluttered with type-casts is unsafe • ClassCastException • goals: readability robustness • compiler-guaranteed type-safety Vladimír Mencl Enter event name 19 Generics: Motivational Example List myIntList = new LinkedList(); myIntList.add(new Integer(0)); Integer x = (Integer)myIntList.iterator().next(); • vs. List<Integer> myIntList = new LinkedList<Integer>(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next(); • explicit typecast removed • compile-time guarantee vs. runtime check Vladimír Mencl Enter event name 20 Generics: More Elaborate Example public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); } ... ?expanded??? into public interface IntegerList { void add(Integer x) Iterator<Integer> iterator(); } No. No code is generated. Generics Elaborated • not C++: no code generated • erasure all type-parameter information discarded at compile time most generic type (typically Object) substituted in bytecode • raw types permitted for interoperability generate warnings Vladimír Mencl Enter event name 22 Generics: Type Rules • no change in type parameter permitted • illegal: List<String> ls = new ArrayList<String>(); List<Object> lo = ls; • why? lo.add(new Object()); // 3 String s = ls.get(0); Vladimír Mencl Enter event name 23 Generics: Type Rules • wildcards void printCollection( Collection<?> c) • upper bound public void drawAll( List<? extends Shape> shapes) { ... } Shape is upper bound of ? • lower bound public static <T> void Reference(T referent, ReferenceQueue<? super T> queue); referent can be inserted into queue of a super-type of T Vladimír Mencl Enter event name 24 Generics: Advanced • arrays of parameterized types hard to check • can be assigned to Object supported as array types not supported as array objects List<String>[] lsa = new List<String>[10]; //cannot instantiate array of param-type List<String>[] lsa = new List<?>[10]; //incompatible types List<String>[] lsa = new List[10]; //unchecked warning Generics: Advanced II • class java.lang.Class<E> E – the type represented by the instance • runtime type token MyType mo = myFactory.create(MyType.class) public static <T> T create(Class<T> c) { return c.newInstance(); }; • ... generic method (must be static) Vladimír Mencl Enter event name 26 Generic: Enum Example public class Enum<E extends Enum<E>> public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> Vladimír Mencl Enter event name 27 Generics: Most Advanced • JDK 1.4: public static Object max(Collection coll) • after elaborate generification public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) Vladimír Mencl Enter event name 28 Enhanced For-loop • Avoid always-repeated glue-code on iteration over collections and arrays void cancelAll(Collection<TimerTask> c) { for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); ) i.next().cancel(); // vs. ((TimerTask)i.next()).cancel(); } void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) t.cancel(); } Vladimír Mencl Enter event name 29 For-loop: Technicalities • new interface Iterable public interface Iterable<T> { Iterator<T> iterator() } retrofitted into Collections Vladimír Mencl Enter event name 30 For-loop: Technicalities (cont.) • Syntax: EnhancedForStatement: for ( FormalParameter : Expression ) Statement expression: Iterable[<E>] or array • Semantics: for ( Iterator<E> #i = Expression.iterator(); #i.hasNext(); ) { FormalParameter = #i.next(); Statement } type of formal parameter must be E or Object Vladimír Mencl Enter event name 31 Autoboxing and unboxing • Automate conversion between primitive types and object wrappers • Example: 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); Vladimír Mencl Enter event name 32 Var-args • syntactic sugar for wrapping variable number of arguments into Object[] • compatible with previous API • integrates with autoboxing public static String format(String pattern, Object... arguments); MessageFormat.format("format", new Object[] { new Integer(1), "" }); => MessageFormat.format("format", 1, "" ); Vladimír Mencl Enter event name 33 Static import • Import static members (fields & methods) into local namespace • Example: import static java.lang.Math.PI; or en masse: import static java.lang.Math.*; double r = cos(PI * theta); // avoids Math.cos, Math.PI • Use sparingly!!! Vladimír Mencl Enter event name 34 References • http://java.sun.com/j2se/1.5.0/docs/ relnotes/features.html => http://java.sun.com/j2se/1.5.0/docs/guide/lan guage/enums.html ... Vladimír Mencl Enter event name 35