LoginSignup
2
3

More than 3 years have passed since last update.

Groovy超簡単入門

Last updated at Posted at 2020-02-09

Groovyの紹介

Groovyは2003年開発されたJavaプラットフォームで動作する動的プログラミング言語であり、直接スクリプトで実施することを特徴としています。

Groovyプロジェクト作成

まずは、簡単なJava Beanを作ります。


public class Cat{

    /**The name of the cat*/
    private String name;

    /**The age of the cat*/
    private int age;

    /**Constuct*/
    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**Get the cat name*/
    String getName() {
        return name
    }

    /**Set the cat name*/
    void setName(String name) {
        this.name = name
    }

    /**Get the cat age*/
    int getAge() {
        return age
    }

    /**Get the cat age*/
    void setAge(int age) {
        this.age = age
    }
}

GroovyとJavaの比較

GroovyとJavaを比べると以下の特徴を持っています。

  1. 行末のセミコロンは省略できる。
  2. returnは省略できる。
  3. getter/setterは自動で作られる。
  4. == によるオブジェクトの比較は、自動的に equals による比較となり、null チェックの必要がない。

public class Cat {
    private String name  /**The name of the cat*/
    private int age /**The age of the cat*/
    /**Constuct*/
    public Cat(String name, int age) {
        this.name = name
        this.age = age
    }
}

Cat cat = new Cat("wow", 1);
print cat.name;

NullPointerException チェック

public class Cat {
    private String name  /**The name of the cat*/
    private int age /**The age of the cat*/
    /**Constuct*/
    public Cat(String name, int age) {
        this.name = name
        this.age = age
    }
}

Cat cat = new Cat("wow", 1);
print cat.name;
Cat cat1 = null
print cat == cat1

コンパイル成功!

スクリーンショット 2020-02-09 16.22.21.png

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3