「Java」演算子instanceofでオブジェクトの型(BigDecimal)を判定するサンプル

書式
obj変数名 instanceof String
obj変数名 instanceof Double)
obj変数名 instanceof BigDecimal
使用例

package com.arkgame.study.tm;

import java.math.BigDecimal;

public class FieldInfoGetDemo {

      public static void main(String[] args) {

            String strA = "test2020";
            Integer itB = 145;
            Double dbC = 145.23;
            BigDecimal bdD = new BigDecimal("256.33");

            //関数を呼び出す
            toObjFunc(strA);
            toObjFunc(itB);
            toObjFunc(dbC);
            toObjFunc(bdD);
      }
      // instanceof演算子を利用
      public static void toObjFunc(Object obj) {
            if (obj instanceof String) {
                  System.out.println("string -> object: " + obj.toString());
            } else if (obj instanceof Integer) {
                  System.out.println("Integer -> object: " + obj.toString());
            } else if (obj instanceof Double) {
                  System.out.println("Double -> object: " + obj.toString());
            } else if (obj instanceof BigDecimal) {
                  System.out.println("BigDecimal -> object: " + obj.toString());
            }

      }

}

実行結果
string -> object: test2020
Integer -> object: 145
Double -> object: 145.23
BigDecimal -> object: 256.33

Java

Posted by arkgame