In several places, I have some code that looks like the following, the only difference is in the type of listener.
public class CustomFragment extends android.app.Fragment {
SomeListener listener;
@Override
public void onAttach(android.app.Activity activity) {
super.onAttach(activity);
// duplication
// ||
// \||/
// \/
try {
listener = (SomeListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SomeListener");
}
}
}
To avoid duplication, I wrote this simple class:
public class TypeConvertor {
private final Object whatNeedToCast;
public static TypeConvertor cast(Object whatNeedToCast) {
return new TypeConvertor(whatNeedToCast);
}
private TypeConvertor(Object whatNeedToCast) {
this.whatNeedToCast = whatNeedToCast;
}
public <OtherType> OtherType to(Class<OtherType> toWhichToCast) {
try {
return (OtherType) whatNeedToCast;
} catch (ClassCastException e) {
throw new ClassCastException(
whatNeedToCast.toString() + " must implement " + toWhichToCast.getName()
);
}
}
}
And the previous code is simplified to the following:
public class CustomFragment extends android.app.Fragment {
SomeListener listener;
@Override
public void onAttach(android.app.Activity activity) {
super.onAttach(activity);
listener = TypeConvertor.cast(activity).to(SomeListener.class);
}
}
But I do not like name TypeConvertor. Help me pick a better name (and help refactor this simple class if needed).