Tuesday Brown Bag

Download Report

Transcript Tuesday Brown Bag

Tuesday
Brown Bag
New Java
Features
(from Java 5 & 6)
01/26/07
© 2006, uXcomm Inc.
Slide 1
Presentation Contents
•
•
•
•
•
•
• Scripting in Java 6
Generics
Enhanced for Loop • Other Java 6
• Includes SQL DBMS
Autoboxing
(Apache's Derby)
Enumerations
• Monitoring
Variable Arguments
• Better Performance
• Updated XML APIs
Annotations
• Example using Junit
• Other Java 5
01/26/07
© 2006, uXcomm Inc.
Slide 2
Generics
• Containers (collections) now have a type
// Removes 4-letter words from c. Elements must be strings
static void expurgate (Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}
01/26/07
© 2006, uXcomm Inc.
Slide 3
Generics Advantages
• More of a specification is in signature
• Errors are now caught at compile-time
Not at run-time with ClassCastException
• Flag warnings with the Eclipse IDE
• Can work for more than just collections
• Generic type information is present only at
compile time
• May fail when interoperating with ill-behaved legacy code
01/26/07
© 2006, uXcomm Inc.
Slide 4
Caveats to Generics
• May not use generics if deploy the
compiled code on a pre-5.0 VM.
• Straightforward to use, but not to write
• Similarity with C++ Templates are
superficial
• Do not generate a new class for each
specialization
• Do not permit “template metaprogramming”
01/26/07
© 2006, uXcomm Inc.
Slide 5
Enhanced for Loop
• Iterations are now straight-forward
• Preserves all of the type safety
void cancelAll ( Collection<TimerTask> c ) {
for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
i.next().cancel();
}
void cancelAll(Collection<TimerTask> c) {
for (TimerTask t : c)
t.cancel();
}
01/26/07
© 2006, uXcomm Inc.
Slide 6
Nested for loops
// BROKEN - throws NoSuchElementException!
for (Iterator i = suits.iterator(); i.hasNext(); )
for (Iterator j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(i.next(), j.next()));
for (Iterator i = suits.iterator(); i.hasNext(); ) {
Suit suit = (Suit) i.next();
for (Iterator j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(suit, j.next()));
}
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
01/26/07
© 2006, uXcomm Inc.
Slide 7
Works for Arrays too
• Deals with end of the array automatically
// Returns the sum of the elements of a
int sum (int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
Note: Can't use it everywhere, for you may
need the index value or access to iterator.
01/26/07
© 2006, uXcomm Inc.
Slide 8
Autoboxing
• Treat an Integer like an int
• Helpful on collections (can't store primitives)
public int fiveMore (Integer v) {
return v + 5;
}
public Integer fiveMore (int v) {
return v + 5;
}
Note: If you autounbox a null, it will
throw a NullPointerException
01/26/07
© 2006, uXcomm Inc.
Slide 9
Enumerations
• final static int has problems:
•
•
•
•
Not typesafe:
setColor ( WINTER );
No namespace: SEASON_WINTER
Brittleness. Must recompile clients if changed
Printed values are uninformative
• Could create a new “Enum” class. Ugh!
• Now enums look like C, C++ and C#
enum Season { WINTER, SPRING, SUMMER, FALL }
01/26/07
© 2006, uXcomm Inc.
Slide 10
Enumeration Features
• The enum declaration defines a class
•
•
•
•
•
•
Not integers ... keeps original “name”
Work with generics and new “for” syntax
Provides implementations of Object methods
They are Comparable and Serializable
The class made by enum is immutable
Add arbitrary methods and fields to an enum
type, and to implement arbitrary interfaces
01/26/07
© 2006, uXcomm Inc.
Slide 11
Extending Enums
public enum
MERCURY
VENUS
EARTH
Planet {
(3.303e+23, 2.4397e6),
(4.869e+24, 6.0518e6),
(5.976e+24, 6.37814e6) ...
private final double mass;
// in kilograms
private final double radius; // in meters
}
01/26/07
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass()
{ return mass; }
public double radius() { return radius; }
© 2006, uXcomm Inc.
Slide 12
EnumSet and EnumMap
• Create a set containing either a range:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY... }
for ( Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY) )
System.out.println(d);
• Or specific members:
EnumSet.of(Style.BOLD, Style.ITALIC)
• This is very efficient (backed by bitmap)
01/26/07
© 2006, uXcomm Inc.
Slide 13
Variable Arguments
• Methods can be defined like a C function:
String format(String pat, Object...
args);
• Must be the last argument (obviously)
• Call method with comma-separated items:
format("On {0,date}: {1}", date, msg);
• Can pass in an array instead
• Now have a C-style printf:
System.out.printf(
"passed=%d; failed=%d%n", passed,
01/26/07
© 2006, uXcomm Inc.
failed);
Slide 14
Annotations
• Markers in your source code for tools
• Don't do anything explicitly
• Stored in both the source and class files
• Replaces ad hoc methods
• Built using features like Reflection
• Side-files that need to be maintained
• Easy to make your own annotations
01/26/07
© 2006, uXcomm Inc.
Slide 15
JUnit 3 Example
public class CalculatorTest extends TestCase
{
public void setup() { ... }
public void teardown() { ... }
public void testDivisionByZero() {
boolean testPassed = false;
try {
new Calculator().divide( 4, 0 );
} catch (ArithmeticException e) {
testPassed = true;
}
assertTrue(testPassed);
}
}
01/26/07
© 2006, uXcomm Inc.
Slide 16
JUnit 4 Example
public class CalculatorTest
{
@Before
public void prepareTestData() { ... }
@After
public void cleanupTestData() { ... }
}
01/26/07
@Test (expected=ArithmeticException.class)
public void divisionByZero() {
new Calculator().divide( 4, 0 );
}
© 2006, uXcomm Inc.
Slide 17
JUnit 4 Details
• Implements a @beforeclass and
@afterclass that is only run once per
class, not for each and every test
• Create parameterized tests that execute
the same tests with different data
• Implements a
@Ignore("Not running because...")
• Implements a @Test (timeout=5000)
01/26/07
© 2006, uXcomm Inc.
Slide 18
Other Java 5 Features
• Formatted input and ouput:
System.out.printf()
• Importing static methods
import static java.awt.BorderLayout.*;
• Concurrency Utility library provides
•
•
•
•
•
Executors (thread task framework)
Thread safe queues
Timers
Locks (including atomic ones)
Semaphores
01/26/07
© 2006, uXcomm Inc.
Slide 19
Scripting Support
• Allows any Java application to execute
“scripts” from a variety of languages
• The scripts have access to Java objects
• The scripts can return data back to Java
• Caveat: The scripting language must be
written for the JVM (implemented in Java)
• Ruby scripts ... JRuby
• Python scripts ... Jython
• Comes with Javascript by default
01/26/07
© 2006, uXcomm Inc.
Slide 20
Scripting Example
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine rubyEngine = m.getEngineByName("jruby");
Bindings bindings = rubyEngine.createBindings ();
bindings.put ("y", new Integer(4));
String script = "x = 3
\n" +
"2 + x + $y";
try {
Object results = rubyEngine.eval(script, bindings);
System.out.println (results);
} catch (ScriptException e) {
e.printStackTrace();
}
01/26/07
© 2006, uXcomm Inc.
Slide 21