2014-10-28 39 views
7

我試圖轉換一些使用Jackson的@JsonSubTypes註釋來管理多態的Java代碼。如何在Kotlin中使用Jackson JsonSubTypes註釋

這裏是工作的Java代碼:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.PROPERTY, 
    property = "type") 
@JsonSubTypes({ 
    @JsonSubTypes.Type(value = Comment.class, name = "CommentNote"), 
    @JsonSubTypes.Type(value = Photo.class, name = "PhotoNote"), 
    @JsonSubTypes.Type(value = Document.class, name = "DocumentNote") 
}) 
public abstract class Note implements Identifiable { 
    [...] 

這裏是科特林代碼,我覺得這是等價的:

JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.PROPERTY, 
    property = "type") 
JsonSubTypes(
    JsonSubTypes.Type(value = javaClass<Comment>(), name = "CommentNote"), 
    JsonSubTypes.Type(value = javaClass<Photo>(), name = "PhotoNote"), 
    JsonSubTypes.Type(value = javaClass<Document>(), name = "DocumentNote") 
) 
abstract class Note : Identifiable { 
    [...] 

,但我得到的這三個「JsonSubTypes以下錯誤。類型「行:

Kotlin: An annotation parameter must be a compile-time constant 
Kotlin: Annotation class cannot be instantiated 

任何想法?

回答

6

在編譯器中發現它是bug,這要感謝他們的報告。要解決這個問題,你可以導入JsonSubTypes.Type並使用它無資質:

import org.codehaus.jackson.annotate.JsonSubTypes.Type 

JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.PROPERTY, 
    property = "type") 
JsonSubTypes(
    Type(value = javaClass<Comment>(), name = "CommentNote"), 
    Type(value = javaClass<Photo>(), name = "PhotoNote"), 
    Type(value = javaClass<Document>(), name = "DocumentNote") 
) 
abstract class Note : Identifiable { 
    [...] 
4

我相信這已經得到解決,現在你可以寫這樣的:

import com.fasterxml.jackson.annotation.JsonSubTypes 
import com.fasterxml.jackson.annotation.JsonTypeInfo 

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME, 
    include = JsonTypeInfo.As.PROPERTY, 
    property = "type") 
    @JsonSubTypes(
     JsonSubTypes.Type(value = Comment::class, name = "CommentNote"), 
     JsonSubTypes.Type(value = Photo::class, name = "PhotoNote"), 
     JsonSubTypes.Type(value = Document::class, name = "DocumentNote")) 
interface Note 

注意的船級符號中JsonSubTypes.Type

+0

對不起,我無法再檢查,但我仍然有一個問題。 是否需要'.java'屬性調用?例如'value = Comment :: class.java' – clemp6r 2015-11-09 08:57:27

+1

編譯器不會抱怨。它在我使用.java屬性時會執行。該解決方案適用於我的項目。 – 2015-11-09 11:17:38