240 likes | 253 Views
Primary Source: New Features and Enhancements J2SE 5.0 http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html. Java SE 5 TM Language Feature Enhancement. Goals. Become familiar with Java SE 5 Language Feature Enhancements required by Java EE 5 used in class examples. Objectives.
E N D
Primary Source: New Features and Enhancements J2SE 5.0 http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html Java SE 5TMLanguage FeatureEnhancement
JavaSE 5 Language Enhancements Goals • Become familiar with Java SE 5 Language Feature Enhancements • required by Java EE 5 • used in class examples
JavaSE 5 Language Enhancements Objectives • Generics • Enhanced for loop • Autoboxing/Unboxing • Typesafe Enums • Varargs • Static Import • Metadata (Annotations)
Generics: Raw Types private static class TestType { public String name; } List rawCollection = new ArrayList(); rawCollection.add(anObject); //the cast to (TestType) is required here TestType rawObject = (TestType)rawCollection.get(0); log.info("raw way=" + rawObject.name); • Provide no means to express type to the compiler • Require syntactical cast (“hope it works”) • Potential runtime failure (ClassCastException) JavaSE 5 Language Enhancements
Generics: <Typed> List<TestType> typedCollection = new ArrayList<TestType>(); typedCollection.add(anObject); //no cast necessary TestType typedObject = typedCollection.get(0); log.info("typed way=" + typedObject.name); • Allow code to express type in Collection • “Typed Collection” • Compiler can check types during compilation • No checks last beyond compile time • allows integration with legacy code JavaSE 5 Language Enhancements
JavaSE 5 Language Enhancements Generics: No Runtime Checks List<TestType> typedCollection = new ArrayList<TestType>(); //typed collections get checked at compile time typedCollection.add(anObject); //but things can still happen that bypass compiler List rawCollection = typedCollection; try { rawCollection.add(new String("slipped by 2")); } catch (ClassCastException ex) { fail("unexpected catch of raw Collection"); } • Legacy code can still cause errors
JavaSE 5 Language Enhancements Generics: Checked Collections //checked collections verify types at runtime List<TestType> checkedCollection = Collections.checkedList(typedCollection, TestType.class); rawCollection = checkedCollection; boolean wasCaught = false; try { rawCollection.add(new String("caught")); } catch (ClassCastException ex) { log.info("caught you!"); wasCaught = true; } assertTrue("checked type not caught", wasCaught); • Checked Collection wrappers will defend collections at insertion • legacy code will be in stack trace
JavaSE 5 Language Enhancements Enhanced For Loop • Iterators • ugly to work with • prone to errors • erroneous placement of calls to next() • Enhanced For Loops • syntactically simpler • manages iterator • not usable when logic requires access to iterator • itr.remove()
JavaSE 5 Language Enhancements For Each Loop: Collections Collection<String> collection = new ArrayList<String>(); collection.add(new String("1")); //... //legacy way int i=0; for(Iterator<String> itr = collection.iterator(); itr.hasNext(); ) { log.info(itr.next()); i++; } assertTrue("unexpected count:" + i, i==collection.size()); //java SE 5 way int i=0; for(String s: collection) { log.info(s); i++; } assertTrue("unexpected count:" + i, i==collection.size());
JavaSE 5 Language Enhancements For Each Loop: Arrays String[] array = new String[3]; array[0] = new String("1"); //... //legacy way int i=0; for(i=0; i<array.length; i++) { log.info(array[i]); } assertTrue("unexpected count:" + i, i==array.length); //java SE 5 way int i=0; for(String s: array) { log.info(s); i++; } assertTrue("unexpected count:" + i, i==array.length);
JavaSE 5 Language Enhancements Autoboxing • Java collections prohibit adding primitive types • must wrap in object type • collection.add(new Integer(1)); • Autoboxing • automatically wraps primitive types in object wrapper when needed • Auto-unboxing • automatically extracts the primitive type from the object wrapper when needed
JavaSE 5 Language Enhancements Autoboxing Example private Integer passInteger(Integer i) { log.info("received Integer=" + i); return i; } private Long passLong(Long i) { log.info("received Long=" + i); return i; } //parameter values being manually wrapped //return values being manually wrapped int intWrap = passInteger(new Integer(1)).intValue(); long longWrap = passLong(new Long(1)).longValue(); //parameter values being automatically wrapped (“auto boxing”) //return values being automatically unwrapped (“auto unboxing“) int intBox = passInteger(1); long longBox = passLong(1L);
JavaSE 5 Language Enhancements Autoboxing and Varargs private int sumArray(Integer[] values) { int result = 0; for (int i=0; i<values.length; i++) { result += values[i]; } return result; } private int sumArgs(int...values) { int result = 0; for(int value : values) { result += value; } return result; } int result1 = sumArray(new Integer[] { new Integer(1), new Integer(2), new Integer(3)}); assertTrue("...:" + result1, result1 == 6); int result2 = sumArgs(4, 5, 6); assertTrue("...:" + result2, result2 == 15);
JavaSE 5 Language Enhancements Enums • “static final int” Approach • Not typesafe • Not namespaced • relies on text prefixes • Brittle • values compiled into client classes • No information in printed values • Java SE 4 enums • full fledge classes • Must be accounted for in O/R Mapping
JavaSE 5 Language Enhancements Enums: names and ordinal values private enum Day { SUN, MON, TUE, WED, THU, FRI, SAT }; public void testEnum() { Day day1 = Day.SUN; Day day2 = Day.WED; log.debug("day1=" + day1.name() + ", ordinal=" + day1.ordinal()); log.debug("day2=" + day2.name() + ", ordinal=" + day2.ordinal()); assertTrue(day1 + " wasn't before " + day2, day1.compareTo(day2) < 0); } (EnumTest.java:testEnum:17) -day1=SUN, ordinal=0 (EnumTest.java:testEnum:18) -day2=WED, ordinal=3
JavaSE 5 Language Enhancements Enums: values private enum Rate { SUN(2), MON(1), TUE(1), WED(1), THU(1), FRI(1), SAT(1.5); double amount; private Rate(double amount) { this.amount = amount; } public double amount() { return amount; } } public void testEnumValues() { int hours = 4; Double wage = 10.0; for (Rate rate : Rate.values()) { Double pay = hours * wage * rate.amount(); log.info("pay for " + rate.name() + "=" + pay); } } (EnumTest.java:testEnumValues:36) -pay for SUN=80.0 (EnumTest.java:testEnumValues:36) -pay for MON=40.0 (EnumTest.java:testEnumValues:36) -pay for TUE=40.0 (EnumTest.java:testEnumValues:36) -pay for WED=40.0 (EnumTest.java:testEnumValues:36) -pay for THU=40.0 (EnumTest.java:testEnumValues:36) -pay for FRI=40.0 (EnumTest.java:testEnumValues:36) -pay for SAT=60.0
JavaSE 5 Language Enhancements Enums: behavior private enum Worker { HARD { public String go() { return "CAN DO!"; } }, GOOD { public String go() { return "I'll try"; } }, BAD { public String go() { return "Why?"; } }; public abstract String go(); } public void testEnumBehavior() { for (Worker w : Worker.values()) { log.info(w.name() + " worker says \'" + w.go() + "\' when tasked"); } } (EnumTest.java:testEnumBehavior:48) -HARD worker says 'CAN DO!' when tasked (EnumTest.java:testEnumBehavior:48) -GOOD worker says 'I'll try' when tasked (EnumTest.java:testEnumBehavior:48) -BAD worker says 'Why?' when tasked
JavaSE 5 Language Enhancements Static Imports • Condition • Frequent use of static methods from another class • Solutions • Reference through interface type • Test.assertTrue(...) • verbose and inconvenient • Implement interface • public class MyClass implements MyType, Test { ... • void foo() { assertTrue(..) • Anti-Pattern • interfaces should define type (MyType), not implementation (Test) • Static imports • import static junit.framework.Test; • public class MyClass implements MyType { ... • void foo() { assertTrue(..)
JavaSE 5 Language Enhancements Annotations • Frameworks (e.g., EJB, JAX-WS, JAXB) require significant amounts boiler-plate code • Implementation of these classes is tedious • Can be generated through metadata • Metadata provided through ... • implementing interface getters() • again, tedious • implementing separate descriptors • enough! too tedious • annotating javadoc • nice start • information lost after source code processed • Java SE 5 Metadata • allows implementation metadata to stay with class • available at runtime
JavaSE 5 Language Enhancements Declaring Annotation Types import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //CallMe.java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CallMe { int order(); String alias() default ""; } //Alias.java @Retention(RetentionPolicy.RUNTIME) public @interface Alias { String value(); } • Each method • declares a property • Default values make them optional • property name'value' used for Annotated Typeswith single property
JavaSE 5 Language Enhancements Declaring Annotations with Class @Alias("demo class") public class MyAnnotatedClass { private static final Log log = ...; @CallMe(order=3, alias="last") public void one() { log.info("one called"); } public void two() { log.info("two called"); } @CallMe(order=0) @Alias("first") public void three() { log.info("three called"); } @CallMe(order=1, alias="middle") public void four() { log.info("four called"); } }
JavaSE 5 Language Enhancements Using Annotations (at Runtime) private void invoke(Object obj) throws Exception { Class clazz = obj.getClass(); log("class annotations", clazz.getAnnotations()); for(Method m : clazz.getDeclaredMethods()) { log(m.getName() + " annotations", m.getAnnotations()); } } -class annotations contained 1 elements -@ejava.examples.javase5.Alias(value=demo class) -one annotations contained 1 elements -@ejava.examples.javase5.CallMe(alias=last, order=3) -two annotations contained 0 elements -three annotations contained 2 elements -@ejava.examples.javase5.CallMe(alias=, order=0) -@ejava.examples.javase5.Alias(value=first) -four annotations contained 1 elements -@ejava.examples.javase5.CallMe(alias=middle, order=1)
JavaSE 5 Language Enhancements Summary • Generics • add compiler checks • do not add code (optional Checked Collection classes) • Enhanced Iterators • mostly for show - opinion • Autoboxing • partially for show - opinion • simplifies component integration • Varargs • useful • Enums • type-safe, flexible value declarations • new type to map to database • Static Imports • eliminates temptation to add implementation to interface • Annotations • provides efficient expression of class properties • key addition in language to provide Java EE 5 “simplicity” requirement
JavaSE 5 Language Enhancements References • http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html