4

In some case, when accessing an activity field from an anonymous class, I get NoSuchFieldError at runtime: java.lang.NoSuchFieldError: MyActivity.myField

EDIT: I'm now sure that it's an Android issue, because everything compiles correctly but resolved incorrectly at runtime. When changing to MyActivity.this.myField instead of plain myField, everything works perfect.

BTW, I rechecked and I don't have any other myField anywhere else, Also, when opening declaration in Eclipse, it goes to the intended field (myField).

The only problem is that I couldn't reproduce this in a sample project. I'm left only to state that it's a specific problem in my project, but I'm reluctant doing so and I can't publish this project.

I'll keep this open in case someone stumbles upon something similar.

Here's the code that I can publish that crashes my project but not the sample one:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MyActivity.this, myField.getName(), Toast.LENGTH_SHORT).show();
        }
    }.run();
}
4

1 に答える 1

0

It seems that accessing the field with the class' prefix solves it: MyActivity.this.myField

Strange. I guess it's something with Android's field resolution in runtime.

于 2012-06-16T14:36:31.640 に答える