我需要实现一个功能类似于以下的方法:
static <T extends Object> T validateObj (T obj) throws ValidationException {
// ValidationException is a custom Exception class
if (obj == null) {
throw new ValidationException(T.class.getSimpleName() + errorMsgTemplate);
} else {
return obj;
}
}
系统如何使用该函数的示例:
try {
RandomAccessFile file = getFile(pathName, "r"); // Custom method. May return null
file = Validator.validateObj(file);
} catch (Exception e) {
// Handle exception
}
// Use file
在尝试记录错误时,无论传递的实际对象是否为 null
,如何获取每个特定方法调用的 T 的类名?方法调用者始终知道要传递到验证方法的对象变量的类型。
更新:虽然我选择了 Bambino 的答案,但这里也对 StuPointerException 的答案表示赞赏。由于处理现有代码的限制,他的答案更适合我的具体问题。不过,我确实相信 Bambino 的答案总体来说是更正确的实现解决方案。
最佳答案
看看Objects.requireNonNull满足您所需的功能。
关于java - 如何获取在泛型方法调用中传递的类型名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38178474/