/**
* Finds and return mapper by type. Uses registered mappers map if not null to search for candidates and register results in this map.
*/
@Nullable
public static <T> DbMapper<T> findOrResolveMapperByType(@NotNull Class<T> type, @Nullable Map<Class, DbMapper> registeredMappers) {
DbMapper<T> mapper = registeredMappers == null ? null : registeredMappers.get(type);
if (mapper == null) {
// search for a field marked as mapper with valid parameter type
for (Field f : type.getDeclaredFields()) {
int mods = f.getModifiers();
if (Modifier.isStatic(mods) && Modifier.isPublic(mods) && Modifier.isFinal(mods) && f.getType().isAssignableFrom(DbMapper.class)) {
AnnotatedType at = f.getAnnotatedType();
if (at instanceof AnnotatedParameterizedType) {
AnnotatedParameterizedType apt = (AnnotatedParameterizedType) at;
AnnotatedType[] args = apt.getAnnotatedActualTypeArguments();
if (args.length == 1 && args[0].getType() == type) {
Mapper a = f.getAnnotation(Mapper.class);
if (a != null) {
try {
//noinspection unchecked
mapper = (DbMapper<T>) f.get(type);
if (mapper == null) {
throw new IllegalArgumentException("Mapper must not be null: " + f);
}
} catch (IllegalAccessException ignored) { // already checked for 'isPublic' before
}
if (registeredMappers != null) {
if (registeredMappers.containsKey(type)) {
throw new IllegalArgumentException("Found multiple mappers per type: m1: " + mapper + ", m2: " + registeredMappers.get(type));
}
registeredMappers.put(type, mapper);
}
}
}
}
} else {
if (f.getAnnotation(Mapper.class) != null) {
throw new IllegalArgumentException("@Mapper field must be public, static final and have valid parametrized type type: " + f);
}
}
}
}
return mapper;
}
DbImpl.java 文件源码
java
阅读 54
收藏 0
点赞 0
评论 0
项目:mjdbc
作者:
评论列表
文章目录