[英]How to tell if a primitive type was cast into an object in Java?
在Java中,請考慮以下代碼:
int myPrimitiveInt = 5;
Integer myObjectInt = 4;
Object fromPrimitive = myPrimitiveInt;
Object fromObject = myObjectInt;
System.out.println(fromPrimitive.getClass());
System.out.println(fromObject.getClass());
System.out.println(int.class);
並輸出:
class java.lang.Integer
class java.lang.Integer
int
我想要的是一種方法來獲得第一個println
的輸出int
。
為什么? 你會問。 好吧,首先,我想知道這樣的事情是否可行。
但其背后的實際原因是一個抽象層,用於通過反射測試具有基本類型參數的私有方法。 最小代碼:
package testing;
import java.lang.reflect.Method;
public class Testing {
private static void doStuff(int a) {
System.out.println("primitive: " + ((Object) a).getClass());
}
public static void main(String[] args) throws ReflectiveOperationException {
Reflect.reflect(Testing.class, "doStuff", 10);
}
}
abstract class Reflect {
static Object reflect(Class<?> clazz, String methodName, Object arg) throws ReflectiveOperationException {
Method method = clazz.getDeclaredMethod(methodName, arg.getClass());
method.setAccessible(true);
return method.invoke(null, arg);
}
}
輸出:
Exception in thread "main" java.lang.NoSuchMethodException: testing.Testing.doStuff(java.lang.Integer)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at testing.Reflect.reflect(Testing.java:17)
at testing.Testing.main(Testing.java:11)
預期產量:
primitive: class java.lang.Integer
甚至更好(如果可能的話):
primitive: int
注意:我知道我可以做clazz.getDeclaredMethod(methodName, int.class)
。 這篇文章的重點是使這個過程更抽象。 請不要給我答案,建議將參數類型傳遞給reflect
方法!
Object x = 10
時會發生什么 int
是自動裝箱的 ,使其成為值為10的Integer
。
因為具有自動裝箱的值10的整數與具有值10的另一個整數之間沒有區別
您需要為原始值添加單獨的方法來重載,這些方法可以處理原始值,因此它們不會被自動裝箱。
原始類型永遠不會“強制轉換”為對象。
基元可以被“自動裝箱”到對象中,但是你永遠無法在代碼中確定這一點,因為自動裝箱只是編譯器添加的代碼,與你手工添加的代碼無法區分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.