Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0

Similar presentations


Presentation on theme: "Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0"— Presentation transcript:

1 Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0 http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html

2 Enterprise Java v070123JavaSE 5 Language Enhancements2 Goals Become familiar with Java SE 5 Language Feature Enhancements –required by Java EE 5 –used in class examples

3 Enterprise Java v070123JavaSE 5 Language Enhancements3 Objectives Generics Enhanced for loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)

4 Enterprise Java v070123JavaSE 5 Language Enhancements4 Generics: Raw Types Provide no means to express type to the compiler Require syntactical cast (“hope it works”) –Potential runtime failure (ClassCastException) 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);

5 Enterprise Java v070123JavaSE 5 Language Enhancements5 Generics: 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 List typedCollection = new ArrayList (); typedCollection.add(anObject); //no cast necessary TestType typedObject = typedCollection.get(0); log.info("typed way=" + typedObject.name);

6 Enterprise Java v070123JavaSE 5 Language Enhancements6 Generics: No Runtime Checks List typedCollection = new ArrayList (); //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

7 Enterprise Java v070123JavaSE 5 Language Enhancements7 Generics: Checked Collections //checked collections verify types at runtime List 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

8 Enterprise Java v070123JavaSE 5 Language Enhancements8 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()

9 Enterprise Java v070123JavaSE 5 Language Enhancements9 For Each Loop: Collections Collection collection = new ArrayList (); collection.add(new String("1")); //... //legacy way int i=0; for(Iterator 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());

10 Enterprise Java v070123JavaSE 5 Language Enhancements10 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);

11 Enterprise Java v070123JavaSE 5 Language Enhancements11 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

12 Enterprise Java v070123JavaSE 5 Language Enhancements12 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);

13 Enterprise Java v070123JavaSE 5 Language Enhancements13 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);

14 Enterprise Java v070123JavaSE 5 Language Enhancements14 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

15 Enterprise Java v070123JavaSE 5 Language Enhancements15 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

16 Enterprise Java v070123JavaSE 5 Language Enhancements16 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

17 Enterprise Java v070123JavaSE 5 Language Enhancements17 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

18 Enterprise Java v070123JavaSE 5 Language Enhancements18 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(..)

19 Enterprise Java v070123JavaSE 5 Language Enhancements19 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

20 Enterprise Java v070123JavaSE 5 Language Enhancements20 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 Types with single property

21 Enterprise Java v070123JavaSE 5 Language Enhancements21 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"); } }

22 Enterprise Java v070123JavaSE 5 Language Enhancements22 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)

23 Enterprise Java v070123JavaSE 5 Language Enhancements23 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

24 Enterprise Java v070123JavaSE 5 Language Enhancements24 References http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html


Download ppt "Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0"

Similar presentations


Ads by Google