【发布时间】:2017-11-15 10:52:15
【问题描述】:
问题:我们需要为不同类别的对象获取一个(字符串)键。 为了可扩展性,我们想要配置方法来获取密钥字符串——而不是使用 intanceOf 实现许多 if-else……
简单的解决方案(带有示例数据)是:
public static String getKey(Object object, Map<Class<?>, Method> keySources) {
Method source = keySources.get(object.getClass());
if (source == null) {
return null;
}
try {
return (String) source.invoke(object);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException("Error at 'invoke': " + e.getMessage(), e);
}
}
public static void main(String[] args) {
Map<Class<?>, Method> keySources = new HashMap<>();
try {
keySources.put(String.class, String.class.getMethod("toString"));
keySources.put(Thread.class, Thread.class.getMethod("getName"));
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException("Error at 'getMethod': " + e.getMessage(), e);
}
System.out.println(getKey("test", keySources));
System.out.println(getKey(new Thread("name"), keySources));
}
所需的解决方案如下:
public static String getKey(Object object, Map<Class<?>, Function<Object, String>> keySources) {
Function<Object, String> source = keySources.get(object.getClass());
if (source == null) {
return null;
}
return source.apply(object);
}
public static void main(String[] args) {
Map<Class<?>, Function<Object, String>> keySources = new HashMap<>();
keySources.put(String.class, String::toString);
keySources.put(Thread.class, Thread::getName);
System.out.println(getKey("test", keySources));
System.out.println(getKey(new Thread("name"), keySources));
}
但是String::toString 给出编译错误:The type String does not define toString(Object) that is applicable here
约束:我们不能修改类,因为它们是生成的。
【问题讨论】:
标签: java reflection lambda