Java 5 Features

Post on 07-Dec-2014

1031 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Audience: Vodafone Germany team at IBM Global Services

Transcript

IBM Global Business Services

04/10/23 Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Shashank Raj H,

10-Sept-2010

Java 5 features

KBA/COM Managed Services

2 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Topics

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

KBA/COM Managed Services

3 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Generics

List myIntList = new LinkedList(); // 1myIntList.add(new Integer(0)); // 2Integer x = (Integer) myIntList.iterator().next(); // 3

The idea behind generics is to enable the programmer to express his intention

List<Integer> myIntList = new LinkedList<Integer>(); // 1myIntList.add(new Integer(0)); //2Integer x = myIntList.iterator().next(); // 3 –No cast required

Compiler can check the type correctness at compile time.Improved readability and robustness.

Introduction

Cluttered

Runtime error

KBA/COM Managed Services

4 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Small excerpt from the definitions of the interfaces List and Iterator in package

java.util:

public interface List<E> {

void add(E x);

Iterator<E> iterator();

}

public interface Iterator<E> {

E next();

boolean hasNext();

}

all occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (in this case, Integer).

Generics Defining Simple Generics

KBA/COM Managed Services

5 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

List<String> ls = new ArrayList<String>(); //1

List<Object> lo = ls; //2

ILLEGAL !!

Line 2 is a compile time error.

Generics Generics and sub typing

KBA/COM Managed Services

6 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

void printCollection(Collection<Object> c) {

for (Object e : c) {

System.out.println(e);

}}

Using wildcards

void printCollection(Collection<?> c) {

for (Object e : c) {

System.out.println(e);

}}

Collection<?> c = new ArrayList<String>();

c.add(new Object()); // compile time error

Generics Wildcards

Object is not the supertype

for all kinds of collections.

Collection of unknown

KBA/COM Managed Services

7 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

public void drawAll(List<Shape> shapes) {

for (Shape s: shapes) {

s.draw(this);

}

}

drawAll() can only be called on lists of exactly Shape:

it cannot, for instance, be called on a List<Circle>

public void drawAll(List<? extends Shape> shapes) { ... }

Generics Bounded Wildcards

Shape

Circle Rectangle

KBA/COM Managed Services

8 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

static void fromArrayToCollection(Object[] a, Collection<?> c) {

for (Object o : a) {

c.add(o); // compile time error

}}

We cannot just shove objects into a collection of unknown type.

static <T> void fromArrayToCollection(T[] a, Collection<T> c) {

for (T o : a) {

c.add(o); // correct

}}

Generics Generic methods

KBA/COM Managed Services

9 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

Topics

KBA/COM Managed Services

10 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

FOR loop

int arr[5] = {2,4,8,16,32};

for (int i=0; i<5; i++)

System.out.println("Output: " + arr[i]);

ENHANCED FOR loop

for(int a:arr)

System.out.println("Output: "+ a); // array index not required

Enhanced for loop Introduction

KBA/COM Managed Services

11 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Dependence on iterator

List<Integer> numbers = new ArrayList<Integer>();

numbers.add(1);numbers.add(2);numbers.add(3);

Iterator<Integer> numbersIterator = null;

for( numbersIterator = numbers.iterator() ; numbersIterator.hasNext() ; ) { System.out.println(numbersIterator.next());;

}

No dependence on iterator with enhanced for loop

for(Integer number : numbers) {

System.out.println(number); }

Enhanced for loop Collections with enhanced for loop

KBA/COM Managed Services

12 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

It is advantageous because It is very convenient for the programmer to iterate over a collection of elements.

It has the following drawbacks:-

-Step value cannot be incremented.

-Backward traversal is not possible.

Enhanced for loop Overview

KBA/COM Managed Services

13 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Topics

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

KBA/COM Managed Services

14 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Repetitive work of converting the primitive types into wrapper classes and vice - versa.

Purpose of conversion is just for some API call.

Auto-boxing and Auto-Unboxing enables the primitive types to be converted into respective wrapper objects and the other way around.

Autoboxing / Unboxing Purpose

KBA/COM Managed Services

15 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Before Java 5

int intPrimitive = intObject.intValue();

intPrimitive++;

intObject = new Integer(intPrimitive);

Using Java 5

Integer intObject = new Integer(10);

intObject++;

Autoboxing / Unboxing Introduction

KBA/COM Managed Services

16 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Boolean isValid = false; // Boxing

Short shortObject = 200; // Boxing

if(shortObject<20){ // unboxing

}

ArrayList<Integer> list = new ArrayList<Integer>();

for(int i = 0; i < 10; i++){

list.add(i); // Boxing

}

Autoboxing / Unboxing Example

KBA/COM Managed Services

17 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Topics

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

KBA/COM Managed Services

18 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

public static final int COLOR_RED= 0;

public static final int COLOR_BLUE = 1;

public static final int COLOR_GREEN = 2;

This pattern has many problems, such as:

Not typesafe

No namespace

Printed values are uninformative.

Typesafe enums Previous approach

KBA/COM Managed Services

19 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

public enum Color {

RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE }

The enumerated types RED, BLUE, YELLOW etc. are of type Color.

Enums are full-fledged java classes and can have arbitrary methods and fields.

Enums can implement interfaces.

Enums can have constructors and they take arguments in the declaration as shown in the next slide.

Typesafe enums Example

Java.lang.Enum

Color

KBA/COM Managed Services

20 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

public enum Color {

RED(625, 740),

ORANGE(590, 625),

YELLOW(565, 590)

//Electro-magnetic Spectrum wavelength in nm

int startWavelength; int endWavelength;

Color(start, end) {

this.startWavelength = start; this.endWavelength = end; }

public int getStartWavelength() {

return startWavelength; }

public int getEndWavelength() {

return endWavelength; }

public static void main(String[] args) {

System.out.println("Red color's wavelength range, " + RED.getStartWavelength()+" ~ "+RED.getEndWavelength()); } }

Typesafe enums Example

Data members

Constructors

Methods

KBA/COM Managed Services

21 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

If the implementation of methods vary for each Constant, then you can implement the methods specific to a constant.

public enum Color {

RED { public Color complimentary() { return GREEN; }},

BLUE { public Color complimentary() { return ORANGE; }},

YELLOW { public Color complimentary() { return PURPLE; }},

...

public abstract Color complimentary(); }

Typesafe enums Example

KBA/COM Managed Services

22 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Topics

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

KBA/COM Managed Services

23 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Int add (int a,int b,intc c);

Int add (int a,int b,int c,int d);

Int add (int a,int b,int c,int d,int e);

Can be replaced by a single method declaration which had VAR ARGS

Int add (int… numbers){

for ( int a : numbers)

sum+=a;

return sum;

}

Variable arguments Example

KBA/COM Managed Services

24 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Legal:

void doStuff(int... x) { } // expects from 0 to many ints

// as parameters

void doStuff2(char c, int... x) { } // expects first a char,

// then 0 to many ints

void doStuff3(Animal... animal) { } // 0 to many Animals

Illegal:

void doStuff4(int x...) { } // bad syntax

void doStuff5(int... x, char... y) { } // too many var-args

void doStuff6(String... s, byte b) { } // var-arg must be last

Variable arguments Examples

KBA/COM Managed Services

25 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

Topics

KBA/COM Managed Services

26 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Consider the java example:

Import java.lang.math.*;

double r = Math.cos ( Math.PI * theta );

More readable form:

Import static java.lang.math.PI;

Import static java.lang.math.cos;

double r = cos ( PI * theta );

Static import Example

KBA/COM Managed Services

27 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Topics

Generics

Enhanced for Loop

Autoboxing/Unboxing

Typesafe Enums

Varargs

Static Import

Metadata (Annotations)

KBA/COM Managed Services

28 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Annotations are metadata i.e. data about data.

They convey semantic information of the code to the compiler.

@interface MyAnno{

String str();

int val();

}

Classes , methods , fields , parameters , and enum constants can be annotated.

@MyAnno(str = “Annotation example”, val=100)

Public static void myMeth(){ …..

Metadata (Annotations) Introduction

KBA/COM Managed Services

29 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

@ClassLevelAnnotation(arg1="val1", arg2={"arg2.val1","arg2.val2"})

public class AnnotationExample {

@FieldLevelAnnotation()

public String field;

@CtorLevelAnnotation()

public AnnotationsTest() {

// code }

@MethodLevelAnnotationA("val")

@MethodLevelAnnotationB(arg1="val1",arg2="val2")

public void someMethod(String string) {

// code }

}

Metadata (Annotations) Example

KBA/COM Managed Services

30 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

@Retention(retention-policy) – determines at what point an annotation is discarded.

Metadata (Annotations) Retention policy

@Retention ( RetentionPolicy. )SOURCECLASSRUNTIME

Discarded by compilerStored in class file. Discarded by JVM. Stored in class file.

Utilized by JVM.

KBA/COM Managed Services

31 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

@interface MyAnno{

String str() default “Testing”;

int val() default 9000;

}

Class Meta{

@MyAnno

Public static void myMeth(){

Meta ob=new Meta();

try{

Class c=ob.getClass();

Method m=c.getMethod(“myMeth”);

MyAnno anno=m.getAnnotation(MyAnno.class);

}catch()….

Metadata (Annotations) Using reflection and default values

KBA/COM Managed Services

32 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Metadata (Annotations)

Annotations

Normal annotations

Single member annotation

Marker annotations

Categories

KBA/COM Managed Services

33 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Normal Annotations — Annotations that take multiple arguments.

@MyNormalAnnotation(mem1="val1", mem2="val2")

public void someMethod() { ... }

Single Member Annotations — An annotation that only takes a single argument has a more compact syntax. You don't need to provide the member name.

@MySingleMemberAnnotation("a single value")

public class SomeClass { ... }

Marker Annotations — These annotations take no parameters. They are used to mark a Java element to be processed in a particular way.

@Deprecated

public void doWork() { ... }

Metadata (Annotations) Categories

KBA/COM Managed Services

34 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

@Retention

@Inherited

@Target

@Documented

@Override

@Deprecated

@SupressWarnings

Metadata (Annotations) Pre built annotations

Meta Annotations

KBA/COM Managed Services

35 04/10/23Vodafone / IBM Confidential | © Copyright IBM Corporation 2010

Thank You !!

top related