01/26/07© 2006, uXcomm Inc. Slide 1 Tuesday Brown Bag with Howard Abrams New Java Features (from...

Post on 31-Mar-2015

213 views 1 download

Tags:

Transcript of 01/26/07© 2006, uXcomm Inc. Slide 1 Tuesday Brown Bag with Howard Abrams New Java Features (from...

01/26/07 © 2006, uXcomm Inc. Slide 1

Tuesday Tuesday Brown BagBrown Bag

with Howar

d Abram

s

New JavaFeatures

(from Java 5 & 6)

01/26/07 © 2006, uXcomm Inc. Slide 2

Presentation ContentsPresentation Contents

• Generics• Enhanced for Loop• Autoboxing• Enumerations• Variable Arguments• Annotations

• Example using Junit

• Other Java 5

• Scripting in Java 6• Other Java 6

• Includes SQL DBMS(Apache's Derby)

• Monitoring• Better Performance• Updated XML APIs

01/26/07 © 2006, uXcomm Inc. Slide 3

GenericsGenerics

• Containers (collections) now have a type// Removes 4-letter words from c. Elements must be stringsstatic 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 4

Generics AdvantagesGenerics 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 5

Caveats to GenericsCaveats 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 6

Enhanced for LoopEnhanced 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 7

Nested for loopsNested 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 8

Works for Arrays tooWorks for Arrays too

// Returns the sum of the elements of aint sum (int[] a) { int result = 0; for (int i : a) result += i; return result;}

• Deals with end of the array automatically

Note: Can't use it everywhere, for you mayneed the index value or access to iterator.

01/26/07 © 2006, uXcomm Inc. Slide 9

AutoboxingAutoboxing

• 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 10

EnumerationsEnumerations

• 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 11

Enumeration FeaturesEnumeration 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 12

Extending EnumsExtending Enums

public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6) ...

private final double mass; // in kilograms private final double radius; // in meters

Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } public double mass() { return mass; } public double radius() { return radius; }}

01/26/07 © 2006, uXcomm Inc. Slide 13

• Create a set containing either a range:

• Or specific members:

• This is very efficient (backed by bitmap)

EnumSet and EnumMapEnumSet and EnumMap

enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY... }

for ( Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY) ) System.out.println(d);

EnumSet.of(Style.BOLD, Style.ITALIC)

01/26/07 © 2006, uXcomm Inc. Slide 14

Variable ArgumentsVariable 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, failed);

01/26/07 © 2006, uXcomm Inc. Slide 15

AnnotationsAnnotations

• 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 16

JUnit 3 ExampleJUnit 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 17

JUnit 4 ExampleJUnit 4 Example

public class CalculatorTest {

@Before public void prepareTestData() { ... }

@After public void cleanupTestData() { ... }

@Test (expected=ArithmeticException.class) public void divisionByZero() { new Calculator().divide( 4, 0 ); }}

01/26/07 © 2006, uXcomm Inc. Slide 18

JUnit 4 DetailsJUnit 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 19

Other Java 5 FeaturesOther Java 5 Features

• Formatted input and ouput: System.out.printf()

• Importing static methodsimport 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 20

Scripting SupportScripting 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 21

Scripting ExampleScripting 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();}