суббота, 8 сентября 2012 г.

Enums and annotations

Personally I have never used these Java features. But they might not be surprising to you.

The first one

Enum defines a class, so I can use it just like any normal class: create constructor, add methods, fields and so on. For example:


    enum BeadType {

        ROUND_BEAD(10, 10), 
        CYLINDRIC_BEAD(10, 15), 
        OTHER_BEAD(20, 20);

        private final int width;
        private final int height;

        BeadType(int w, int h) {
            this.width = w;
            this.height = h;
        }

        public int getW() {
            return width;
        }

        public int getH() {
            return height;
        }
    }

I really like it.

The second one

Annotations. I suppose, that almost everyone has at least once used @Override annotation. But did you know that you can create your own type of annotation and even make it to be documented in your Javadoc-documentation (just add @Documeted before your own annotation definition). I was surprised!

    @Documented
    @interface MyAnnotation {

        String myName();

        int myAge();

        String email();
    }

    @MyAnnotation(
            myName = "Nastya",
            myAge = 20,
            email = "zminyty@gmail.com")