javaで基本データの種類を判断する方法

8121 ワード

インターネット上ではinstance ofで直接判断する方法が多いです。二つの方法をまとめました。
変数がintかどうかを判断する場合を例にして、直接コードを付けます。
方法1:

public class test { public static void main(String[] args){ test t=new test(); int int_num=0; double double_num=0; System.out.println(t.judgeType(int_num)); System.out.println(t.judgeType(double_num)); } public boolean judgeType(Object temp){ if(temp instanceof Integer) return true; else return false; } }

方法二:

public class test { public static void main(String[] args){ try{ Scanner input=new Scanner(System.in); int i=input.nextInt(); System.out.println(" "); } catch(Exception e){ System.out.println(" "); } } }

方法は、一度にinstance of演算子を使用して、基本データタイプとその包装類の自動変換の特徴を利用して、多状態を運用して、基本データタイプを判断する目的を達成する。
方法二は異常処理を運用する知識である。やや巧妙である。