PHP*_*ger 1 java casting overloading
请看下面的类,我需要检查变量中是否有有效值.如果在变量中有适当的值而不是,那么一切正常null.当它变为null时,行为不是我所期望的(尽管如果Integer a = null;选中a instanceof Integer,则可能有意义,
有人可以指导我如何从下面的课程中获得正确的结果吗?
package com.mazhar.hassan;
public class ValueChecker {
public static boolean empty(Integer value) {
System.out.println("Integer");
return (value != null && value.intValue() > 0);
}
public static boolean empty(Long value) {
System.out.println("Long");
return (value != null && value.longValue() > 0);
}
public static boolean empty(String value) {
System.out.println("String");
return (value != null && value.length() > 0);
}
public static boolean empty(Object value) {
System.out.println("Object");
return (value != null);
}
public static void checkAll(Object... args) {
for(Object o: args) {
if (o instanceof Integer) {
empty((Integer)o);
}
else if (o instanceof Long) {
empty((Long)o);
}
else if (o instanceof String) {
empty((String)o);
}
else {
empty(o);
}
}
}
public static void main (String[] args) {
Integer a = null;
Long b = null;
String x = null;
Object y = null;
if (a instanceof Integer) {
System.out.println("a is Integer");
} else {
System.out.println("a is not Integer");
}
System.out.println("/---------------------------------------------------/");
checkAll(a,b,x,y);
System.out.println("/---------------------------------------------------/");
empty(a);
empty(b);
empty(x);
empty(y);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我需要精确的类型检查,我想抛出像"无效整数","无效长"等错误.
上述类的输出如下.
/-----------------------(Output 1)----------------------------/
a is not Integer
/-----------------------(Output 2)----------------------------/
Object
Object
Object
Object
/------------------------(Output 3)---------------------------/
Integer
Long
String
Object
Run Code Online (Sandbox Code Playgroud)
输出1:a不是整数(由instanceof检查)无法识别它但传递给重载函数时会转到右边的函数(输出3)
输出2:如何checkAll使用多个/动态param checkAll(varInt,varLong,varString,varObject)实现
输出1的行为是由于在编译时绑定了方法重载这一事实引起的.因此,在程序运行之前绑定的特定重载是绑定的.instanceof另一方面,是运行时检查.
因此,在运行时a instanceof Integer是有效的null instanceof Integer,这显然是false.
但是对于每个单独的方法调用,都会调用正确的方法,因为编译器会根据变量的引用类型在编译时绑定方法的特定重载.从而:
empty(a); // Compiled to a call to empty(Integer value)
empty(b); // Compiled to a call to empty(Long value)
empty(x); // Compiled to a call to empty(String value)
empty(y); // Compiled to a call to empty(Object value)
Run Code Online (Sandbox Code Playgroud)
所以不管实际对象的a,b,x,和y参考,您总能获得您的控制台上的正确输出相应的对象.
输出2:如何使用多个/动态参数checkAll(varInt,varLong,varString,varObject)实现checkAll
好吧,如果你要通过null,你不能真的.null是null在运行时,并没有与之相关的任何类型的信息.JVM无法判断一个null是" String null"还是" Object null".这只是null.因此,您无法真正实现您想要null输入的多重检查- null instanceof ______将始终返回false,因此您将始终以默认情况结束.
但是,如果传递实际对象,则该方法应该正常工作.