Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and...

24
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

Transcript of Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and...

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

EnterpriseJava

Java SE 5TM

Language FeatureEnhancement

Primary Source:New Features and Enhancements

J2SE 5.0http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html

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

v070123 JavaSE 5 Language Enhancements 2

EnterpriseJava

Goals

• Become familiar with Java SE 5 Language Feature Enhancements– required by Java EE 5– used in class examples

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

v070123 JavaSE 5 Language Enhancements 3

EnterpriseJava

Objectives

• Generics• Enhanced for loop• Autoboxing/Unboxing• Typesafe Enums• Varargs• Static Import• Metadata (Annotations)

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

v070123 JavaSE 5 Language Enhancements 4

EnterpriseJava

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);

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

v070123 JavaSE 5 Language Enhancements 5

EnterpriseJava

Generics: <Typed>

• 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<TestType> typedCollection = new ArrayList<TestType>(); typedCollection.add(anObject); //no cast necessary TestType typedObject = typedCollection.get(0); log.info("typed way=" + typedObject.name);

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

v070123 JavaSE 5 Language Enhancements 6

EnterpriseJava

Generics: No Runtime ChecksList<TestType> typedCollection = new ArrayList<TestType>(); //typed collections get checked at compile timetypedCollection.add(anObject); //but things can still happen that bypass compilerList 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

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

v070123 JavaSE 5 Language Enhancements 7

EnterpriseJava

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

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

v070123 JavaSE 5 Language Enhancements 8

EnterpriseJava

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()

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

v070123 JavaSE 5 Language Enhancements 9

EnterpriseJava

For Each Loop: CollectionsCollection<String> collection = new ArrayList<String>();collection.add(new String("1"));//...

//legacy wayint 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 wayint i=0;for(String s: collection) { log.info(s); i++;}assertTrue("unexpected count:" + i, i==collection.size());

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

v070123 JavaSE 5 Language Enhancements 10

EnterpriseJava

For Each Loop: ArraysString[] array = new String[3];array[0] = new String("1");//... //legacy wayint 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);

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

v070123 JavaSE 5 Language Enhancements 11

EnterpriseJava

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

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

v070123 JavaSE 5 Language Enhancements 12

EnterpriseJava

Autoboxing Exampleprivate 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 wrappedint 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);

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

v070123 JavaSE 5 Language Enhancements 13

EnterpriseJava

Autoboxing and Varargsprivate 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);

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

v070123 JavaSE 5 Language Enhancements 14

EnterpriseJava

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

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

v070123 JavaSE 5 Language Enhancements 15

EnterpriseJava

Enums: names and ordinal valuesprivate 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

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

v070123 JavaSE 5 Language Enhancements 16

EnterpriseJava

Enums: valuesprivate 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

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

v070123 JavaSE 5 Language Enhancements 17

EnterpriseJava

Enums: behaviorprivate 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

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

v070123 JavaSE 5 Language Enhancements 18

EnterpriseJava

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(..)

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

v070123 JavaSE 5 Language Enhancements 19

EnterpriseJava

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

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

v070123 JavaSE 5 Language Enhancements 20

EnterpriseJava

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

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

v070123 JavaSE 5 Language Enhancements 21

EnterpriseJava

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"); }}

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

v070123 JavaSE 5 Language Enhancements 22

EnterpriseJava

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 [email protected](value=demo class)-one annotations contained 1 [email protected](alias=last, order=3)-two annotations contained 0 elements-three annotations contained 2 [email protected](alias=, order=0)[email protected](value=first)-four annotations contained 1 [email protected](alias=middle, order=1)

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

v070123 JavaSE 5 Language Enhancements 23

EnterpriseJava

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

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

v070123 JavaSE 5 Language Enhancements 24

EnterpriseJava

References

• http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html