Add annotation to field defined in parent class
I have an abstract base class and two child classes; I have a "same" field in two child classes, annotated to each other with "different" annotations, and I want to put the "up" field in the base class and add annotations to the child classes.
Maybe? (after non-working pseudocode)
abstract class Base {
Object field;
}
class C1 extends Base {
@Annotation1
super.field;
}
class C2 extends Base {
@Annotation2
super.field;
}
source to share
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 classes Fragment
:
@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
}
}
source to share
You cannot "override" a field in java, so strictly speaking you cannot do what you want.
Overall, it seems odd that the "same" field requires different annotations, suggesting that there might be something wrong with your design, but it's hard to tell without knowing the specifics.
Most annotations work with accessors in the same way as with member fields. So, what you can do is to make your field private and provide for him setField()
and getField()
. Then you can override them in subclasses and annotate in different ways.
source to share