Search code examples
javaannotationsandroid-annotations

add annotation to a field defined in parent class


I have an abstract base class, and two child classes; I have the "same" field in the two child classes, annotated each other with "different" annotations, and I want to put "up" the field into the base class, and add the annotations in the child classes.

Is possible? (following non-working pseudo-code)

abstract class Base {
    Object field;
}

class C1 extends Base {
    @Annotation1
    super.field;
}

class C2 extends Base {
    @Annotation2
    super.field;
}

Solution

  • Let's say you have these layouts:

    fragment1.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <TextView
            android:id="@+id/commonView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <TextView
            android:id="@+id/viewInFragment1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    fragment2.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <TextView
            android:id="@+id/commonView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <TextView
            android:id="@+id/viewInFragment2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    Then you can have these Fragment classes:

    @EFragment
    public class BaseFragment extends Fragment {
    
        @ViewById
        TextView commonView;
    
        @AfterViews
        void setupViews() {
            // do sg with commonView
        }
    }
    
    @EFragment(R.layout.fragment1)
    public class Fragment1 extends BaseFragment {
    
        @ViewById
        TextView viewInFragment1;
    
        @Override
        void setupViews() {
            super.setupViews(); // common view is set up
    
            // do sg with viewInFragment1
        }
    }
    
    @EFragment(R.layout.fragment1)
    public class Fragment2 extends BaseFragment {
    
        @ViewById
        TextView viewInFragment2;
    
        @Override
        void setupViews() {
            super.setupViews(); // common view is set up
    
            // do sg with viewInFragment2
        }
    }