sealed class Entity
data class Bacteria(
val uid: String,
val rank: String,
val division: String,
val scientificname: String,
val commonname: String
): Entity()
data class CTDDisease(
val diseaseId: String,
val name: String,
val altDiseaseIds: List<String>,
val parentIds: List<String>,
val definition: String?
) : Entity()
然后我想将文档定义为
@Document(collection = "annotations")
data class Annotation(
@Id val id: String,
...
val spans: List<AnnotationSpan>
)
data class AnnotationSpan(
val startIndex: Int,
val endIndex: Int,
val entity: Entity? // Can be Bacteria or Disease or null
)
我还不时接受客户RequestBody
中的这两个类,例如
@PutMapping("/annotations")
fun submitAnnotations(@RequestBody submission: Submissions): Mono<Void> { ... }
data class Submission(val annotations: List<AnnotationSpan>, ...) // AnnotationSpan contains Entity
但我明白了
java.lang.IllegalAccessException: class kotlin.reflect.jvm.internal.calls.CallerImpl$Constructor cannot access a member of class com.package.name.Entity with modifiers "private"
如果我将类Entity
更改为抽象类
abstract class Entity
那我没有收到错误,但是我的查询操作一直持续下去。
Bacteria
和Disease
都有不同的字段,因此它们应该是可区分的。
我尝试使用hacky转换器
@ReadingConverter
class NormalizedEntityReaderConverter: Converter<DBObject, NormalizedEntity> {
override fun convert(source: DBObject): NormalizedEntity? {
println(source.toString())
val gson = Gson()
return gson.runCatching { fromJson(source.toString(), CTDDisease::class.java) }.getOrNull()
?: gson.runCatching { fromJson(source.toString(), Bacteria::class.java) }.getOrNull()
}
}
然后像注册
@Configuration
class MongoConverterConfig {
@Bean
fun customConversions(): MongoCustomConversions {
val normalizedEntityReaderConverter = NormalizedEntityReaderConverter()
val converterList = listOf<Converter<*, *>>(normalizedEntityReaderConverter)
return MongoCustomConversions(converterList)
}
}
我的转换器在手动调用时似乎可以正常工作,但是由于某些原因,Spring仍然没有使用它。
我是Spring的新手。通过在TypeScript中使用联合类型,可以在Node.js服务器中实现此功能。
interface AnnotationSpan {
startIndex: number;
endIndex: number;
entity?: Bacteria | Disease;
}
如何实现这种行为?