gpt4 book ai didi

java:如何知道对象内部变量的类型?

转载 作者:行者123 更新时间:2023-12-02 16:16:12 24 4
gpt4 key购买 nike

我有以下代码:

void testme(Object a) {
# printing the type of the variable transferred to the function
}

我如何知道传递给该函数的变量的类型?例如,如果用户执行以下函数,我如何知道差异:

Integer a=5;
testme(a);

String a="a";
testme(a);

一般来说,我正在构建一个通用函数来使用我的数据库,并且我需要使用 setLong/setInt/setString 取决于传输到函数的变量类型。

有什么想法吗?

谢谢

最佳答案

您可以使用instanceof和/或getClass。前者针对特定类进行测试,后者实际上为您提供参数的 Class 对象(String.class 等)。例如:

if (a instanceof String) {
// ...
}
else if (a instanceof Integer) {
// ...
}
// ...

但对于您的具体情况,您可能可以使用 PreparedStatement#setObject 的版本之一.

关于java:如何知道对象内部变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4584742/

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