Is it possible to call internal method (without visibility operator) from a class inherited from another package?

5

Problem

I'm trying to create some extra behaviors on some native Android components.

For this I am creating a class above the Android component and rewriting some situations that I want to behave differently, and I came across a situation that I need in my custom method, calling a method of% inherited% if the Android component), but the method is not accessible for my class , since it is internal and not class , and my protected is in another class .

Questions?

  • Despite knowing that package attributes and methods are only accessible for members of the same internal Java, I would like to know if there are any way to access these methods from a package of a other class ?
  • And optionally, if there is any other way to overwrite native components of Android, who can avoid this kind of problem?

Example of what I'm trying to do:

public class MeuAbsListView extends AdapterView<ListAdapter>{

    public MeuAbsListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void meuMetodoDisparadoPeloMeuEvento(){
        // faz seu comportamento custumizado ... 

        // e tem esse metodo 'rememberSyncState' do 'AdapterView' que preciso chamar
        // só que ele é internal e não tenho acesso a ele, 
        // já no AbsListView nativo é possivel pois ele é do mesmo package do AdapterView
        rememberSyncState();
    }   
}

In the Android AdapterView font method is declared as follows:

void rememberSyncState() {
    // codigo do rememberSyncState ...
}
    
asked by anonymous 29.07.2014 / 20:20

1 answer

5

Two ways to achieve this through emergency technical adaptations (a.k.a Gambiarra ).

It works in java but not on android

1. Create a third heir class in the same restrictive class package

public class ClasseRestritiva
{
   protected void foo(){}
}

and

public MinhaClasseNaoRestritiva extends ClasseRestritiva
{

     public void chamaFoo()
     {
           foo();
     }

}

2. Reflections

There is a good example on this question from SOEN. Also, I recommend that you check official documentation

Solution with Reflection

Method rememberSyncState = AdapterView.class.getDeclaredMethod("rememberSyncState");
// Set accessible provide a way to access private methods too
rememberSyncState.setAccessible(true);
// this é instancia da class que herda de AdapterView
rememberSyncState.invoke(this);
    
29.07.2014 / 20:45