java enums and annotations

22
Enum Types Built-in support for types of discrete values Advantages over C++’s enum: Enum declaration defines a class Type-safety Body can include methods and fields Values may be objects Support for iteration, naming 1

Upload: katina-smith

Post on 22-Nov-2015

20 views

Category:

Documents


0 download

DESCRIPTION

Java Enums Sample Examples written in java

TRANSCRIPT

  • Enum Types

    Built-in support for types of discrete values

    Advantages over C++s enum:

    Enum declaration defines a class

    Type-safety

    Body can include methods and fields

    Values may be objects

    Support for iteration, naming

    1

  • Representing a Set of Predefined Values The Old Way

    public class OldTrafficLight {

    public static final int RED = 1;

    public static final int YELLOW = 2;

    public static final int GREEN = 3;

    private int c = RED;

    public int getColor() {

    return c;

    }

    public void setColor(int newCol) {

    if(newCol >= RED && newCol

  • Representing a Set of Predefined Values With Enum Types

    public class TrafficLight { public enum Colors {

    RED, YELLOW, GREEN

    }

    private Colors c = Colors.RED;

    public Colors getColor() {

    return c;

    }

    public void setColor(Colors newCol) {

    c = newCol;

    }

    }

    3

  • The TrafficLight class - cont.

    public class TrafficLight { ...

    public void setColor(int n) {

    Colors[] temp = Colors.values();

    setColor(temp[n]);

    }

    public boolean isColor(int n) {

    return c.ordinal() == n;

    }

    public void setColor(String colorName) {

    setColor(Colors.valueOf(colorName));

    }

    public boolean isColor(String colorName) {

    return c.name().equals(colorName);

    }

    }

    4

  • Using enum types

    import static TrafficLight.Colors.*;

    public void main() {

    TrafficLight tl = new TrafficLight();

    System.out.println(tl.getColor());

    tl.setColor(YELLOW); //

  • Switching on Enumspublic class TrafficLight {

    ...

    public enum Colors {

    RED, YELLOW, GREEN;

    public Colors next() {

    switch(this) {

    case RED:

    return YELLOW;

    case YELLOW:

    return GREEN;

    default:

    return null;

    }

    }

    6

  • An enum type with methods

    public class TrafficLight {

    public enum Colors {

    RED {

    public Colors next() { return YELLOW; }

    },

    YELLOW {

    public Colors next() { return GREEN; }

    },

    GREEN;

    public Colors next() { return null; }

    }

    private Colors c = Colors.RED;

    public Colors getColor() { return c; }

    public void setColor(Colors nc) { c = nc; }

    }

    7

  • Maps of Enums

    EnumMap is a high performance map implementation for enums.

    Implemented as an array.

    public class TrafficLight {

    EnumMap colorMsgs =

    new EnumMap(Colors.class);

    colorMsgs.put(RED, stop);

    colorMsgs.put(YELLOW, get ready);

    colorMsgs.put(GREEN, go);

    }

    8

  • Enums - Summary

    Enums are classes Extend java.lang.Enum Might implement interfaces

    Enums have no public constructor removes the ability to create additional instances of the enum

    not defined at compile-time

    Enum values are public, static, and final Values cannot be changed The enum cant be subclassed

    Enums override toString( ) TrafficLight.Colors.RED.toString() returns the

    String RED.

    9

  • Annotations

    The goal: Allow the programmer to provide additional information about the program This information can be used by software engineering tools

    An annotation is a type defined using an interface-like syntax

    An annotation can be specified whenever a modifier is allowed Convention: before the public/static modifiers

    Annotations do not affect semantics of the class But may affects semantics of things using the class (tools,

    code generation, runtime options, etc.)

    10

  • Predefined Annotations

    @Override

    Assert intention to override a method in a superclass

    Compiler fails if not actually overriding

    Checks spelling, override vs. overload

    @Deprecated

    Indicates that an element should not be used

    @SuppressWarning

    Tells the compiler to suppress specific warnings

    11

  • Definition of two annotation types

    // Author.java:

    public @interface Author {

    String value() default "Unknown";

    }

    // MethodKind.java:

    import java.lang.annotation.ElementType;

    import java.lang.annotation.Target;

    @Target(ElementType.METHOD)

    public @interface MethodKind {

    boolean composite() default false;

    boolean mutator() default false;

    }

    12

  • Using @overridepackage my.prg;

    public class Rational extends Number {

    private long a, b;

    public Rational(long a, long b) {

    this.a = a;

    this.b = b;

    }

    private Double asDouble() {

    return new Double(a * 1.0 / b);

    }

    @Override

    public short shortValue() {

    return asDouble().shortValue();

    }

    13

  • Using @Author, @MethodKind

    public class Rational extends Number {

    ...

    @Author(value="Pazit")

    @MethodKind(composite=false, mutator=true)

    public void assign(long n) {

    a = n;

    b = 1;

    {

    @Override

    @Author("Pazit")

    @MethodKind(composite=true, mutator=false)

    public byte byteValue() {

    return asDouble().byteValue();

    }

    }

    14

  • Kinds of Annotations

    Marker annotations

    Have no attributes

    @Override, @Deprecated

    Single value annotations

    Provide a single piece of data.

    Attribute type can be primitive, class, enum, or array

    @Author(Pazit)

    @SuppressWarnings({unchecked, deprecation})

    Multi valued annotations

    @MethodKind(composite=true, mutator=false)15

  • What Can Be Annotated?

    Any program element

    Package

    Types

    Class, Interface, Enum definition, Annotation type

    Method, Constructor, Field, Enum constant, Method parameter

    Local varible declaration

    16

  • Meta-Annotations

    Annotations that annotate annotations

    Specify how the annotation should be used @Documented

    Javadoc should be generated when this annotation is applied to an element

    @Inherited Does the annotation get applied to subclasses/

    @Target Where the annotation can be used (source elements)

    Default is all

    @Retention Where is the annotation retained

    17

  • Meta-Annotations Example

    @Target({TYPE, CONSTRUCTOR, FIELD})

    @Retention(RetentionPolicy.RUNTIME)

    Public @interface Marker{}

    @Marker class foo { //OK

    @Marker public foo(){} //OK

    @Marker int x; //OK

    @Marker public void m(){//NO

    @Marker int y; //NO

    }

    }

    18

  • Reflection and Annotations

    Annotations marked with @Retain(RUNTIME) are available via reflection.

    Class, Constructor, Field, Method, Package have methods to handle annotations: isAnnotationPresent

    getAnnotations

    getDeclaredAnnotations

    19

  • Author annotation will be accessible only if its declaration was annotated with @Retention(RUNTIME)

    Inspecting Annotations using Reflection

    20

    public class AuthorPrinter {

    static void printMethodsAuthor(Class c){

    for(Method m: c.getMethods())

    if(m.isAnnotationPresent(Author.class)) {

    Author a = m.getAnnotation(Author.class);

    System.out.println(m.getName() +

    " by " + a.value());

    }

    }

    }

  • Usage Example

    Output is:

    f by Unknown

    g by Pazit

    21

    class TestAnnotations {

    @Author()

    public void f() {}

    @Author("Pazit")

    public void g(){}

    public static void main(String[] args){

    AuthorPrinter.printMethodsAuthor

    (TestAnnotations.class);

    }

    }

  • VarArgs

    22

    private static String format(Object... values) {

    StringBuilder sb = new StringBuilder( );

    for (Object o : values)

    sb.append(o).append(" ");

    return sb.toString( );

    }

    public static void main(String[] args) {

    System.out.print(format(args));

    System.out.print(format());

    System.out.print(format(new Integer(7),

    new Date(),

    hello,

    2));

    }