我用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;
}
发布于 2017-08-16 06:37:58
不同之处在于,对类主体中定义的属性应用注释与在主构造函数中声明的属性注释有何不同。
参见:语言引用中的https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets:
在注释属性或主构造函数参数时,有多个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
)
https://stackoverflow.com/questions/45714575
复制相似问题