我使用Play Framework大约1个月了,这是一个很棒的东西,但我有一个大问题.我尝试在安全控制器中运行以下代码:
MyModel myModel = MyModel.all().first();
Field idField = myModel.getClass().getField("id");
关于第二行Play说:编译错误
The file /app/controllers/Security.java could not be compiled. Error
raised is : Unhandled exception type NoSuchFieldException
也许这是一个核心bug?谢谢。
您应该处理getField(String fieldName)可能抛出的异常。在本例中是NoSuchFieldException。
试着这样写:
Field idField = null;
try {
idField = myModel.getClass().getField("id");
} catch (NoSuchFieldException nsfe) {
throw new RuntimeException(nsfe);
}
如果您使用dp4j的@TestPrivates
或@Reflect(catchExceptions =true)
,则不需要自己编写catch语句:
public class Security{
@Reflect(catchExceptions =true) //when false it will add the exceptions to the throws list.
public void aMethod(){
MyModel myModel = MyModel.all().first();
Field idField = myModel.getClass().getField("id");
//you might as well write:
// int id = myModel.id;
}