Home » Android » java – Why does a protected android:onClick method in Activity actually work?

java – Why does a protected android:onClick method in Activity actually work?

Posted by: admin April 23, 2020 Leave a comment

Questions:

Suppose you define android:onClick="doClick" in your Activity as

protected void doClick(View view) { }

The documentation states that

This name must correspond to a public method that takes exactly one parameter of type View.

This is a given requirement of the underlying Class.getMethod() method, which only finds public methods as the documentation states that it

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

So how is it possible, that this implementation, which should not work at all, works on some devices and emulators, while it doesn’t work on others using the same API levels as well?

How to&Answers:

As per “The Java™ Tutorials” :
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package

Answer:

I debugged the particular implementations. The relevant portion of the code is within the Support Library using Class.getMethod().

As stated in the documentation, this method only finds public member methods and behaves correctly. For some reason, all modifiers of declared protected methods of the Activity (these are onCreate() and doClick()) are set to 1, which means these are actually public.

I could only observe this behavior creating the debug build with a Mac. So why this happens is still an open question, which I’m trying to find an answer to.