Download New language features in JDK 1.5

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
New language features in JDK 1.5:
Enum, Annotations, Generics,
For, Auto(un)boxing, Var-args, Static Import
Vladimir Mencl
DISTRIBUTED SYSTEMS RESEARCH GROUP
http://nenya.ms.mff.cuni.cz/
CHARLES UNIVERSITY IN PRAGUE
Faculty of Mathematics and Physics
JDK 1.5 new language features
• Changes to language and class-file format
ƒ Enumerated types
ƒ Annotations
• metadata
ƒ Generic types
• Similar to C++ templates
• Language shortcuts (no JVM/bytecode
requirements)
ƒ
ƒ
ƒ
ƒ
Vladimír Mencl
Enter event name
Enhanced for loop
Autoboxing/unboxing
Var args
Static import
2
Enums: Traditional Approach
ƒ public static final int COLOR_BLUE = 0;
ƒ public static final int COLOR_GREEN = 1;
ƒ public static final int COLOR_RED = 2;
• severe problems:
ƒ type unsafe (int)
ƒ no namespace
• must prefix COLOR_ to avoid collisions
ƒ constants compiled into clients – must
recompile
ƒ printed value non-informative – is just int
Vladimír Mencl
Enter event name
3
Enums: JDK 1.5
public enum Suit { CLUBS, DIAMONDS,
HEARTS, SPADES }
• fully-fledged class
ƒ inherits from
public abstract class Enum implements
Comparable, Serializable {
ƒ can be forced to implement arbitrary interfaces
• one instance per value
ƒ in public static final self-typed fields
ƒ protected constructor
Vladimír Mencl
Enter event name
4
Enums: Enum Class Methods
• Class getDeclaringClass()
• self-type[] values()
• static self-typed valueOf(Class
enumType, String name)
• toString()
ƒ returns “user-friendly” instance name
• low-level methods:
ƒ String name() name of this enum constant
ƒ int ordinal() // zero based
Vladimír Mencl
Enter event name
5
Enums: Adding Data and Behavior
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS
(4.869e+24, 6.0518e6),
EARTH
(5.976e+24, 6.37814e6),
// constructor arguments
private final double mass;
// in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
}
Vladimír Mencl
Enter event name
6
Enums: Constant Specific Methods
• abstract method declared in type
• concrete methods defined per-constant
public enum Operation {
PLUS
MINUS
TIMES
DIVIDE
{
{
{
{
double
double
double
double
eval(double
eval(double
eval(double
eval(double
x,
x,
x,
x,
double
double
double
double
y)
y)
y)
y)
{
{
{
{
return
return
return
return
x
x
x
x
+
*
/
y;
y;
y;
y;
}},
}},
}},
}};
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
Vladimír Mencl
Enter event name
7
Enums: API Additions
• java.util.EnumSet
ƒ bit-vector implemented
ƒ static EnumSet range(E from, E to)
• java.util.EnumMap
ƒ iterators operate in natural order
ƒ claim: operates in constant time
Vladimír Mencl
Enter event name
8
Annotations
• Metadata
ƒ Ad-hoc mechanisms in past
• transient, @deprecated
• JDK 1.5 annotations
ƒ no direct effect on running program
ƒ used by tools and libraries
• (and these can influence the running program)
• Usage: “can replace”
ƒ BeanInfo class,
ƒ EJB deployment descriptor
Vladimír Mencl
Enter event name
9
Annotation facility
• syntax for
ƒ declaring annotation types
ƒ annotating declarations
• API for reading annotations
• class-file representation
• annotation processing tool (apt)
ƒ usage: implement a visitor class...
Vladimír Mencl
Enter event name
10
Annotation syntax
• (meta-)instance of annotation type
• element types:
ƒ
ƒ
ƒ
ƒ
ƒ
ƒ
primitive
enum
String
Class
annotation
array of these
• elements declared as methods
ƒ “getter” method
ƒ may have a default value
• annotations are special modifiers
ƒ ... public, static, final ,...
Annotation Examples
• Annotation type definition
public @interface RequestForEnhancement {
int
id();
String synopsis();
String engineer() default "[unassigned]";
String date();
default "[unimplemented]";
}
• Annotated method
@RequestForEnhancement(
id
= 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date
= "4/1/3007"
)
public static void travelThroughTime(Date
destination) { ... }
Annotations: More
• Marker annotation type
public @interface Preliminary { }
• May omit parentheses
@Preliminary public class TimeTravel { ... }
• Convention:
ƒ a single element is named “value”
public @interface Copyright {
String value();
}
ƒ then, element name may be omitted
@Copyright("2002 Yoyodyne") public class
OscillationOverthruster { ... }
Vladimír Mencl
Enter event name
13
Annotations: Reflection Example
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
public class Foo {
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
...
import java.lang.reflect.*;
public class RunTests { ...
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class)) {
try {
m.invoke(null);
...
Annotation API
• package java.lang.annotation
ƒ interface Annotation
• method: Class annotationType()
ƒ reflection: java.lang.Class
• isAnnotation() - if this Class represents an
annotation type
• boolean isAnnotationPresent(Class
annotationClass)
• Annotation getAnnotation(Class annotationClass)
Meta-Annotations
• annotation types can have annotations
ƒ => meta annotations
• predefined types
ƒ Retention
• RetentionPolicy() value
ƒ SOURCE – discarded by compiler
ƒ CLASS – store in class file but not in JVM
• (default)
ƒ RUNTIME – retain also in JVM
ƒ ...
Meta-Annotations (cont.)
• Inherited
• Documented
• Target
ƒ ElementType[] value()
ƒ ElementType:
• ANNOTATION_TYPE, CONSTRUCTOR, FIELD,
LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER,
TYPE (includes annotation type)
• Example:
@Documented @Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface Retention {RetentionPolicy
value();
... }
Vladimír Mencl
Enter event name
17
Annotations: Example
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface Author {
String value();
}
@Author(“Vlada") public class MyClass {
public static void main(String[] args) {
Class cl = MyClass.class;
Author author =
(Author)cl.getAnnotation(Author.class);
System.out.println(author.value());
}
}
Generics
• abstraction over types
• types may have a parameter
• motivation: existing code
ƒ is cluttered with type-casts
ƒ is unsafe
• ClassCastException
• goals:
ƒ readability
ƒ robustness
• compiler-guaranteed type-safety
Vladimír Mencl
Enter event name
19
Generics: Motivational Example
List myIntList = new LinkedList();
myIntList.add(new Integer(0));
Integer x = (Integer)myIntList.iterator().next();
• vs.
List<Integer> myIntList =
new LinkedList<Integer>();
myIntList.add(new Integer(0));
Integer x = myIntList.iterator().next();
• explicit typecast removed
• compile-time guarantee vs. runtime check
Vladimír Mencl
Enter event name
20
Generics: More Elaborate Example
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
... ?expanded??? into
public interface IntegerList {
void add(Integer x)
Iterator<Integer> iterator();
}
No. No code is generated.
Generics Elaborated
• not C++: no code generated
• erasure
ƒ all type-parameter information discarded at
compile time
ƒ most generic type (typically Object)
substituted in bytecode
• raw types
ƒ permitted for interoperability
ƒ generate warnings
Vladimír Mencl
Enter event name
22
Generics: Type Rules
• no change in type parameter permitted
• illegal:
List<String> ls = new ArrayList<String>();
List<Object> lo = ls;
• why?
lo.add(new Object()); // 3
String s = ls.get(0);
Vladimír Mencl
Enter event name
23
Generics: Type Rules
• wildcards
void printCollection( Collection<?> c)
• upper bound
public void drawAll(
List<? extends Shape> shapes) { ... }
ƒ Shape is upper bound of ?
• lower bound
public static <T> void Reference(T referent,
ReferenceQueue<? super T> queue);
referent can be inserted into queue of a super-type of T
Vladimír Mencl
Enter event name
24
Generics: Advanced
• arrays of parameterized types
ƒ hard to check
• can be assigned to Object
ƒ supported as array types
ƒ not supported as array objects
List<String>[] lsa = new List<String>[10];
//cannot instantiate array of param-type
List<String>[] lsa = new List<?>[10];
//incompatible types
List<String>[] lsa = new List[10]; //unchecked
warning
Generics: Advanced II
• class java.lang.Class<E>
ƒ E – the type represented by the instance
• runtime type token
MyType mo = myFactory.create(MyType.class)
public static <T> T create(Class<T> c) {
return c.newInstance();
};
• ... generic method (must be static)
Vladimír Mencl
Enter event name
26
Generic: Enum Example
public class Enum<E extends Enum<E>>
public class
EnumMap<K extends Enum<K>,V>
extends AbstractMap<K,V>
Vladimír Mencl
Enter event name
27
Generics: Most Advanced
• JDK 1.4:
public static Object max(Collection coll)
• after elaborate generification
public static <T extends Object &
Comparable<? super T>> T
max(Collection<? extends T> coll)
Vladimír Mencl
Enter event name
28
Enhanced For-loop
• Avoid always-repeated glue-code
ƒ on iteration over collections and arrays
void cancelAll(Collection<TimerTask> c) {
for (Iterator<TimerTask> i =
c.iterator(); i.hasNext(); )
i.next().cancel();
// vs. ((TimerTask)i.next()).cancel();
}
void cancelAll(Collection<TimerTask> c) {
for (TimerTask t : c)
t.cancel();
}
Vladimír Mencl
Enter event name
29
For-loop: Technicalities
• new interface Iterable
public interface Iterable<T> {
Iterator<T> iterator()
}
ƒ retrofitted into Collections
Vladimír Mencl
Enter event name
30
For-loop: Technicalities (cont.)
• Syntax:
ƒ EnhancedForStatement: for ( FormalParameter :
Expression ) Statement
ƒ expression: Iterable[<E>] or array
• Semantics:
for ( Iterator<E> #i = Expression.iterator();
#i.hasNext(); ) {
FormalParameter = #i.next();
Statement
}
ƒ type of formal parameter must be E or Object
Vladimír Mencl
Enter event name
31
Autoboxing and unboxing
• Automate conversion between primitive types
and object wrappers
• Example:
public static void main(String[] args) {
Map<String, Integer> m =
new TreeMap<String, Integer>();
for (String word : args) {
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq+1));
}
System.out.println(m);
Vladimír Mencl
Enter event name
32
Var-args
• syntactic sugar for wrapping variable number of
arguments into Object[]
• compatible with previous API
• integrates with autoboxing
public static String format(String pattern,
Object... arguments);
MessageFormat.format("format", new Object[]
{ new Integer(1), "" });
=>
MessageFormat.format("format", 1, "" );
Vladimír Mencl
Enter event name
33
Static import
• Import static members (fields & methods) into
local namespace
• Example:
import static java.lang.Math.PI;
ƒ or en masse:
import static java.lang.Math.*;
double r = cos(PI * theta);
// avoids Math.cos, Math.PI
• Use sparingly!!!
Vladimír Mencl
Enter event name
34
References
• http://java.sun.com/j2se/1.5.0/docs/
relnotes/features.html
ƒ =>
http://java.sun.com/j2se/1.5.0/docs/guide/lan
guage/enums.html
ƒ ...
Vladimír Mencl
Enter event name
35
Related documents