我有以下代码:
void testme(Object a) {
# printing the type of the variable transferred to the function
}
Run Code Online (Sandbox Code Playgroud)
我如何知道传递给该函数的变量的类型?例如,如果用户执行以下功能,我怎么知道区别:
Integer a=5;
testme(a);
Run Code Online (Sandbox Code Playgroud)
要么
String a="a";
testme(a);
Run Code Online (Sandbox Code Playgroud)
一般来说,我正在构建一个通用函数来处理我的数据库,我需要使用setLong/setInt/setString取决于转移到该函数的变量类型.
有任何想法吗?
谢谢
你可以使用instanceof和/或getClass.前者针对特定类进行测试,后者实际上为您提供了参数的Class对象(String.class等).例如:
if (a instanceof String) {
// ...
}
else if (a instanceof Integer) {
// ...
}
// ...
Run Code Online (Sandbox Code Playgroud)
但是对于您的具体情况,您可以使用其中一个版本PreparedStatement#setObject.
| 归档时间: |
|
| 查看次数: |
349 次 |
| 最近记录: |