使用Java进行类型判断
我需要类似于VB中的TypeOf的东西,但看起来好像没有,所以我自己试着做了一个。
也许没有业务用途,但我是为了学习而想要的。比如《Java编程语言第四版》中第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));
}
}