【发布时间】:2017-11-14 23:00:02
【问题描述】:
用例:接受多种数据类型的用户输入,并在后端使用 Java 验证用户输入。
数据库:
Table 1 - Attribute Declarations
Id | Attribute Name | Attribute Data Type
-----------------------------------------
1 | My Numeric Type | Long.class
2 | My String Type | String.class
3 | Favorite Letter | Character.class
Table 2 - Attribute Assignments
Id | Fk | Attribute Value [Varchar2]
--------------------------
66 | 1 | 1234
67 | 2 | Some Word
68 | 3 | A
问题:如何在不知道它是 Long.class 的情况下将“1234”之类的值转换为 Long.class。我不想硬编码一堆 if-else 块,因为如果我需要向我的数据库添加一个新类,我将需要更改代码以支持它。
伪:
public static void validate(final Class<?> dbClass, String attrValue){
try {
dbClass.cast(attrValue);
} catch(Exception e){
LOGGER.error("ERROR: This Attribute Value is not an "
+ "instance of Class: {} | {}", dbClass.getSimpleName(), e);
throw e;
}
}
当前问题:java.lang.String 不能转换为 Long。我知道我可以使用 Long.parseLong(string) 来做到这一点,但是有没有一种通用的方法可以为我的 DB 中定义的任何类做到这一点?
【问题讨论】:
标签: java validation generics