gpt4 book ai didi

Java 类型转换、对象类型和重载问题

转载 作者:行者123 更新时间:2023-11-29 06:34:20 25 4
gpt4 key购买 nike

请查看以下类,我需要检查变量中是否存在有效值。如果变量中有一个适当的值而不是 null,则一切正常,当它变为 null 时,行为不是我所期望的(尽管如果 Integer a = null; 当检查为 a instanceof Integer 时,

有人可以指导我如何通过后续类(class)获得正确的结果吗?

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);
}
}

我需要精确类型检查的原因是,我必须抛出“无效整数”、“无效长整数”等错误。

上面类的输出如下。

/-----------------------(Output 1)----------------------------/
a is not Integer
/-----------------------(Output 2)----------------------------/
Object
Object
Object
Object
/------------------------(Output 3)---------------------------/
Integer
Long
String
Object

输出 1:a 不是整数(由 instanceof 检查)不能识别它但是当传递给重载函数时转到正确的函数(输出 3)

输出 2:如何使用多个/动态参数 checkAll(varInt, varLong, varString, varObject) 实现 checkAll

最佳答案

输出 1 的行为是由方法重载在编译 时绑定(bind)这一事实引起的。因此要选择的特定重载甚至在程序运行之前就已绑定(bind)。另一方面,instanceof 是运行时检查。

因此,在运行时 a instanceof Integer 实际上是 null instanceof Integer,这显然是 false

但是对于每个单独的方法调用,都会调用正确的方法,因为编译器在编译时根据变量的引用类型绑定(bind)了方法的特定重载。因此:

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)

因此,无论 abxy 引用的实际对象是什么,您对于相应的对象,您始终会在控制台上获得正确的输出。


Output 2: How to achieve checkAll with multiple/dynamic param checkAll(varInt, varLong, varString, varObject)

嗯,如果你要传递 null,你真的不能。 null 在运行时为 null,并且没有任何与之关联的类型信息。 JVM 无法分辨一个 null 是“String null”还是“Object null”。它只是 null。所以你不能真正实现你想要对 null 输入进行的多重检查——null instanceof ______ 将始终返回 false,所以你将始终以您的默认情况结束。

不过,如果您传递实际对象,该方法应该正常工作。

关于Java 类型转换、对象类型和重载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24425730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com