更新时间:2023-11-28 23:29:22
将地图从Class
映射到Predicate
,然后使用该映射为您的课程获取测试对象".这是一个示例:
Make a map from Class
to Predicate
, and use that to obtain a "tester object" for your class. Here is an example:
static Map<Class<?>,Predicate<String>> canParse = new HashMap<>();
static {
canParse.put(Integer.TYPE, s -> {try {Integer.parseInt(s); return true;} catch(Exception e) {return false;}});
canParse.put(Long.TYPE, s -> {try {Long.parseLong(s); return true;} catch(Exception e) {return false;}});
};
您现在可以检索该类的谓词,并测试您的字符串,如下所示:
You can now retrieve a predicate for the class, and test your string, like this:
if (canParse.get(Long.TYPE).test("1234567890123")) {
System.out.println("Can parse 1234567890123");
} else {
System.out.println("Cannot parse 1234567890123");
}
您不必遍历整个测试人员列表;检查只会针对您要测试的类型进行.
You wouldn't have to go though the entire list of testers; the check will happen only for the type that you want to test.