2011-11-17 21 views
0

我使用Play Framework大約1個月,這是一件好事,但我遇到了一個大問題 。 I`ve嘗試在安全控制器運行下面的代碼:未處理的異常類型NoSuchFieldException(java反射)

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

關於2號線戲稱: 編譯錯誤

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

也許它了一個核心的錯誤? 謝謝。

+0

顯示你的模型代碼 – sdespolit

回答

4

你應該處理getField(String fieldName)可以拋出的異常。在這種情況下,一個NoSuchFieldException。

嘗試將其寫爲這樣:

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

加工!謝謝。 – user1051870

1

如果使用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; 
} 
相關問題