user1051870
user1051870

Reputation: 913

Unhandled exception type NoSuchFieldException (java reflection)

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.

Upvotes: 0

Views: 3116

Answers (2)

simpatico
simpatico

Reputation: 11107

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;
}

Upvotes: 1

Hiery Nomus
Hiery Nomus

Reputation: 17769

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);
}

Upvotes: 4

Related Questions