Download slides - jhuep.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Enterprise
Java
TM
5
Java SE
Language Feature
Enhancement
Primary Source:
New Features and Enhancements
J2SE 5.0
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
Goals
Enterprise
Java
• Become familiar with Java SE 5 Language Feature
Enhancements
– required by Java EE 5
– used in class examples
v070123
JavaSE 5 Language Enhancements
2
Objectives
•
•
•
•
•
•
•
Enterprise
Java
Generics
Enhanced for loop
Autoboxing/Unboxing
Typesafe Enums
Varargs
Static Import
Metadata (Annotations)
v070123
JavaSE 5 Language Enhancements
3
Generics: Raw Types
Enterprise
Java
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)
v070123
JavaSE 5 Language Enhancements
4
Generics: <Typed>
Enterprise
Java
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
v070123
JavaSE 5 Language Enhancements
5
Generics: No Runtime Checks
Enterprise
Java
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
v070123
JavaSE 5 Language Enhancements
6
Generics: Checked Collections
Enterprise
Java
//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
v070123
JavaSE 5 Language Enhancements
7
Enhanced For Loop
Enterprise
Java
• 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()
v070123
JavaSE 5 Language Enhancements
8
For Each Loop: Collections
Enterprise
Java
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());
v070123
JavaSE 5 Language Enhancements
9
For Each Loop: Arrays
Enterprise
Java
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);
v070123
JavaSE 5 Language Enhancements
10
Autoboxing
Enterprise
Java
• 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
v070123
JavaSE 5 Language Enhancements
11
Autoboxing Example
Enterprise
Java
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);
v070123
JavaSE 5 Language Enhancements
12
Autoboxing and Varargs
Enterprise
Java
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);
v070123
JavaSE 5 Language Enhancements
13
Enums
Enterprise
Java
• “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
v070123
JavaSE 5 Language Enhancements
14
Enums: names and ordinal values
Enterprise
Java
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)
(EnumTest.java:testEnum:18)
v070123
-day1=SUN, ordinal=0
-day2=WED, ordinal=3
JavaSE 5 Language Enhancements
15
Enums: values
Enterprise
Java
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)
(EnumTest.java:testEnumValues:36)
(EnumTest.java:testEnumValues:36)
(EnumTest.java:testEnumValues:36)
(EnumTest.java:testEnumValues:36)
(EnumTest.java:testEnumValues:36)
(EnumTest.java:testEnumValues:36)
v070123
-pay
-pay
-pay
-pay
-pay
-pay
-pay
for
for
for
for
for
for
for
SUN=80.0
MON=40.0
TUE=40.0
WED=40.0
THU=40.0
FRI=40.0
SAT=60.0
JavaSE 5 Language Enhancements
16
Enums: behavior
Enterprise
Java
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)
(EnumTest.java:testEnumBehavior:48)
(EnumTest.java:testEnumBehavior:48)
v070123
-HARD worker says 'CAN DO!' when tasked
-GOOD worker says 'I'll try' when tasked
-BAD worker says 'Why?' when tasked
JavaSE 5 Language Enhancements
17
Static Imports
Enterprise
Java
• 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(..)
v070123
JavaSE 5 Language Enhancements
18
Annotations
Enterprise
Java
• 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
v070123
JavaSE 5 Language Enhancements
19
Declaring Annotation Types
import
import
import
import
java.lang.annotation.ElementType;
java.lang.annotation.Retention;
java.lang.annotation.RetentionPolicy;
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();
}
v070123
Enterprise
Java
• Each method
declares a property
Default values
make them optional
• property name
'value' used for
Annotated Types
with single property
JavaSE 5 Language Enhancements
20
Declaring Annotations with Class
Enterprise
Java
@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"); }
}
v070123
JavaSE 5 Language Enhancements
21
Using Annotations (at Runtime)
Enterprise
Java
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
[email protected](value=demo class)
-one annotations contained 1 elements
[email protected](alias=last, order=3)
-two annotations contained 0 elements
-three annotations contained 2 elements
[email protected](alias=, order=0)
[email protected](value=first)
-four annotations contained 1 elements
[email protected](alias=middle, order=1)
v070123
JavaSE 5 Language Enhancements
22
Summary
•
•
•
•
•
•
•
Enterprise
Java
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
v070123
JavaSE 5 Language Enhancements
23
References
Enterprise
Java
• http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
v070123
JavaSE 5 Language Enhancements
24