Kotlin变种人

我使用Ektorp作为CouchDB“ORM”,但是这个问题似乎比这个更一般。 有人可以解释什么是区别

@JsonInclude(NON_NULL) abstract class AbstractEntity( id: String?, revision: String? ) { @JsonProperty("_id") val id: String? = id @JsonProperty("_rev") val revision: String? = revision } 

 @JsonInclude(NON_NULL) abstract class AbstractEntity( @JsonProperty("_id") val id: String? = null, @JsonProperty("_rev") val revision: String? = null ) 

对于第一个案件Ektorp不抱怨,但第二个说:

 org.ektorp.InvalidDocumentException: Cannot resolve revision mutator in class com.scherule.calendaring.domain.Meeting at org.ektorp.util.Documents$MethodAccessor.assertMethodFound(Documents.java:165) at org.ektorp.util.Documents$MethodAccessor.<init>(Documents.java:144) at org.ektorp.util.Documents.getAccessor(Documents.java:113) at org.ektorp.util.Documents.getRevision(Documents.java:77) at org.ektorp.util.Documents.isNew(Documents.java:85) 

除此之外,如果我这样做

 @JsonInclude(NON_NULL) abstract class AbstractEntity( @JsonProperty("_id") var id: String? = null, @JsonProperty("_rev") var revision: String? = null ) 

我得到:

 org.ektorp.DbAccessException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "_id" (class com.scherule.calendaring.domain.Meeting), not marked as ignorable 

问题是第一个代码片段与第二个代码片段有什么不同? 在第一种情况下,Ektorp“认为”有一个增变器,但不是在第二个…

这是Ektorp在定位方法(setId,setRevision)时似乎使用的代码片段。

 private Method findMethod(Class<?> clazz, String name, Class<?>... parameters) throws Exception { for (Method me : clazz.getDeclaredMethods()) { if (me.getName().equals(name) && me.getParameterTypes().length == parameters.length) { me.setAccessible(true); return me; } } return clazz.getSuperclass() != null ? findMethod( clazz.getSuperclass(), name, parameters) : null; } 

不同之处在于注解在类体中定义的属性的应用程序与在主构造函数中声明的注释属性不同。

请参阅:语言参考中的注释使用站点目标

注释属性或主构造参数时,有多个Java元素是从相应的Kotlin元素生成的,因此在生成的Java字节码中有多个可能的注释位置。

如果您未指定使用地点目标,则根据所使用的注释的@Target批注选择目标。 如果有多个适用的目标,则使用以下列表中的第一个适用目标:

  • param
  • property
  • field

所以,当你注释一个在主构造函数中声明的属性的时候,它的构造函数参数默认是在Java字节码中获得注解的。 要改变这一点,请明确指定注释目标,例如:

 abstract class AbstractEntity( @get:JsonProperty("_id") val id: String? = null, @get:JsonProperty("_rev") val revision: String? = null ) 
Interesting Posts