未处理的异常类型NoSuchFieldException(java反射)

发布于 2024-12-16 16:11:48 字数 404 浏览 1 评论 0原文

我使用 Play Framework 大约 1 个月,这是一件很棒的事情,但我遇到了一个大问题 。 我尝试在安全控制器中运行以下代码:

MyModel myModel = MyModel.all().first(); 
Field idField = myModel.getClass().getField("id"); 

关于第 2 行 Play 说: 编译错误

The file /app/controllers/Security.java could not be compiled. Error 
raised is : Unhandled exception type NoSuchFieldException 

也许这是一个核心错误? 谢谢。

I am using Play Framework about 1 month and it is a great thing, but I had one big problem
.
I`ve try to run following code in secure controller:

MyModel myModel = MyModel.all().first(); 
Field idField = myModel.getClass().getField("id"); 

About line 2 Play says:
Compilation error

The file /app/controllers/Security.java could not be compiled. Error 
raised is : Unhandled exception type NoSuchFieldException 

Maybe it`s a core bug?
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放我走吧 2024-12-23 16:11:48

您应该处理 getField(String fieldName) 可能引发的异常。在本例中为 NoSuchFieldException。

尝试这样写:

Field idField = null;
try {
    idField = myModel.getClass().getField("id");
} catch (NoSuchFieldException nsfe) {
    throw new RuntimeException(nsfe);
}

You should handle the exception that getField(String fieldName) can throw. In this case a NoSuchFieldException.

Try to write it as such:

Field idField = null;
try {
    idField = myModel.getClass().getField("id");
} catch (NoSuchFieldException nsfe) {
    throw new RuntimeException(nsfe);
}
甜`诱少女 2024-12-23 16:11:48

如果您使用 dp4j@TestPrivates@Reflect(catchExceptions =true)< /code> 您不需要自己编写 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;
}

If you use dp4j's @TestPrivates or @Reflect(catchExceptions =true) you don't need to write the catch statements yourself:

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文