有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Play framework 2.2.0不会自动生成getter/setter

在处理游戏框架时,我发现了一个非常恼人的情况,我不得不花很多时间指出邪恶的根源在哪里

为了简化情况,让我们考虑下面的代码:

controllers.Application.java中:

return ok(views.html.method1.render(Person.find.all());

method1.scala.html中:

@(people : List[Person])
...
@for(person <- people) {
     @person.name
     @person.pet.getName()
     @person.pet.name
}

Person.java中:

@Id
public Long id;
@ManyToOne
public Pet name;
...

问题是当我在Pet类中手动设置getName()方法时。返回该值。 但当我让Play框架自动生成时,它不会返回任何值

当然,Play框架已经为person生成了getter,我可以通过person.name访问它

它不应该自动生成吗


共 (1) 个答案

  1. # 1 楼答案

    http://www.playframework.com/documentation/2.2.x/JavaEbean表示getter和setter是在运行时生成的(对于需要它们的普通旧Java库),在编译时不可见:

    Play has been designed to generate getter/setter automatically, to ensure compatibility with libraries that expect them to be available at runtime (ORM, Databinder, JSON Binder, etc). If Play detects any user-written getter/setter in the Model, it will not generate getter/setter in order to avoid any conflict.

    Caveats:

    (1) Because Ebean class enhancement occurs after compilation, do not expect Ebean-generated getter/setters to be available at compilation time. If you’d prefer to code with them directly, either add the getter/setters explicitly yourself, or ensure that your model classes are compiled before the remainder of your project, eg. by putting them in a separate subproject.

    (2) Enhancement of direct Ebean field access (enabling lazy loading) is only applied to Java classes, not to Scala. Thus, direct field access from Scala source files (including standard Play templates) does not invoke lazy loading, often resulting in empty (unpopulated) entity fields. To ensure the fields get populated, either (a) manually create getter/setters and call them instead, or (b) ensure the entity is fully populated before accessing the fields.

    因此,getter在模板中不可见。 如果您需要延迟加载(请参见2)),我建议您让您的getter和setter由IDE生成。 如果您不需要延迟加载,只需访问字段,它们仍然是public

    顺便说一句:在类Person中引用名为name的类Pet听起来像是一个笨拙的数据模型,无意冒犯