我目前正在嘗試使用System.out.print來發出一個整數x的類型。然而,從我發現的唯一函數simular到typeOf是getClass,它不適用於int或instanceof,它似乎只適用於if。有沒有其他的命令我可以嘗試或我堅持System.out.print("Integer")
?
typeOf沒有使用getClass()或instanceof
-5
A
回答
4
請注意,Java是靜態類型語言。在運行時不需要檢查變量基元類型,因爲它在編譯時已知並且不能更改。例如,如果你聲明
int x = 5;
然後x
不能別的比int
等,所以試圖做類似typeof(x)
(像一些其他語言)是沒有意義的。
可以概括變量類型它分配給Object
引用類型:
int x = 5;
Object obj = x;
但即使在這種情況下obj
不會int
。在這種情況下,Java編譯器會自動將您的x
設爲Integer
類型,因此obj.getClass().getName()
將返回java.lang.Integer
而obj instanceof Integer
將返回true。
1
一般來說,如果你知道這個類型,沒有理由這樣做,你不需要一個函數來爲你工作。
唯一有用的是當你無法計算出類型時,因爲你在學習,而且類型不明顯。你可以使用像這樣的重載函數來實現它。
public static void main(String[] args) {
byte b = 1;
byte a = 2;
System.out.println("The type of a+b is "+typeOf(a+b));
long l = 1;
float f = 2;
System.out.println("The type of l+f is "+typeOf(l+f));
}
public static String typeOf(byte b) {
return "byte";
}
public static String typeOf(char ch) {
return "char";
}
public static String typeOf(short s) {
return "short";
}
public static String typeOf(int i) {
return "int";
}
public static String typeOf(long i) {
return "long";
}
public static String typeOf(float i) {
return "float";
}
public static String typeOf(double i) {
return "double";
}
public static String typeOf(boolean b) {
return "boolean";
}
public static String typeOf(Object o) {
return o.getClass().getName();
}
打印
The type of a+b is int
The type of l+f is float
相關問題
- 1. 如何在QML中做「is_a」,「typeof」或instanceof?
- 2. 在GWT中使用Javascript instanceof&typeof(JSNI)
- 3. Typeof/instanceof類型別名
- 4. 如何在不使用instanceOf或getClass()的情況下知道類的類型?
- 5. JavaScript中typeof和instanceof的區別
- 6. Guice - 測試噴射器的正確行爲 - getClass()vs instanceof
- 7. decltype,result_of或typeof?
- 8. 使用class.isEnum()或instanceof Enum更好嗎?
- 9. typeof運算和運營商的instanceof返回同一變種
- 10. 使用.getclass()的接口
- 11. Uncaught ReferencEerror函數沒有定義,如何使用typeof和if else?
- 12. INSTANCEOF沒有返回正確的答案
- 13. 繼承使用typeof
- 14. JS - 用instanceof顯示圖像或視頻?
- 15. Java:使用getClass獲取子類引用
- 16. Delphi GetClass
- 17. 使用instanceof測試對象
- 18. 使用'instanceof function(){}'的原因?
- 19. 在java中使用instanceof Void
- 20. 使用instanceof運算符
- 21. Java使用instanceof迭代器
- 22. typeof number + typeof number = NaN?
- 23. 使用getClass()加載資源getResource()
- 24. Java工廠使用泛型,.class與.getClass()
- 25. 如何使用的getClass()的getResource()方法
- 26. 捕捉單獨的異常或使用的instanceof - Java 6中
- 27. 區分用typeof()
- 28. 使用slice()有或沒有[end]參數
- 29. 有沒有辦法動態檢查類型的instanceof?
- 30. 有沒有更好的方法來短路一個instanceof鏈?
爲什麼你需要知道一個數的類型?字面本身告訴你它的類型。或者那不是你的意思? –
你想做什麼,爲什麼你需要檢查元素是否是int?請注意,你可以使用'int.class'。 –
我不需要它來檢查,但要給出哪個元素。我試圖找到一種沒有字符串的方法,因爲我會在處理對象時多次改變對象的類型 – byj