0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

IntelliJ IDEAで未実装のtoString()メソッドを追加する

Last updated at Posted at 2014-10-01

IntelliJ IDEAでtoString()が未実装のクラスに対して、toString()を追加する方法を紹介します。

その前になぜtoString()メソッドを実装した方をいいかというと。例えば、このような実装があった場合、

if (debug.messageEnabled()) {
    debug.message("LoginState : " + loginState);
}

toString()が実装されていないと、

LoginState : com.sun.identity.authentication.service.LoginState@3f184740

というように役に立たないログが出力されてしまいます。これでは、デバッグ時に参考にならないので、このクラスのフィールドの情報が出力されるようにtoString()を実装します。しかし、手入力の場合は実装漏れや誤りがあるので、自動生成した方が正確かつ簡単です。

対象のクラスを選択した状態で、Code > Generate をクリックし、その中にあるtoString選択します。
generateToString.png

不要なフィールドは削除してOKボタンをクリックすると、
gen2str.png

以下のようなtoString()が追加されます。

    @Override
    public String toString() {
        return "LoginState{" +
                "orgName='" + orgName + '\'' +
                ", receivedCallbackInfo=" + Arrays.toString(receivedCallbackInfo) +
                ", prevCallback=" + Arrays.toString(prevCallback) +
                ", submittedCallbackInfo=" + Arrays.toString(submittedCallbackInfo) +
                ", callbacksPerState=" + callbacksPerState +
    ...
                ", loginStatus=" + loginStatus +
                ", modulesInSession=" + modulesInSession +
                '}';
    }

上のソースコードから分かるように配列の場合は、Arrays.toString()で各要素を表示してくれたり、文字列の場合はシングルクォートで囲んでくれたりするようです。
自動生成は、toString()以外にもgetter/setterやコピーライトなどいろいろとあります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?