LoginSignup
2
1

More than 5 years have passed since last update.

Java で型判定

Last updated at Posted at 2019-03-17

VB の TypeOf にあたるもの?が欲しかったのですが、なんか無さそうなので作ってみました。

業務の用途はないかもしれませんが学習用に欲しかったのです。プログラミング言語 Java 第4版 の 192 頁にある練習問題とか。

参考:https://stackoverflow.com/questions/3993982/how-to-check-type-of-variable-in-java

class Type {
    static String of(byte x) {
        return (x + " is a byte.");
    }
    static String of(short x) {
        return (x + " is a short.");
    }
    static String of(int x) {
        return (x + " is an int.");
    }
    static String of(float x) {
        return (x + " is a float.");
    }
    static String of(double x) {
        return (x + " is a double.");
    }
    static String of(char x) {
        return (x + " is a char.");
    }
    static String of(boolean x) {
        return (x + " is a boolean.");
    }
    static String of(Object x) {
        final String className = x.getClass().getName();
        return (x + " is instance of " + className);
    }
}
class Main {
    public static void main(String[] args) {
        Type t = new Type();
        System.out.println(Type.of(t));
    }
}

2
1
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
1