I have two ListActivity classes that I want to pass into into a third class as below. The reason being that I'm using the deprecated android.text.ClipboardManager in one activity for old Android versions, and the newer android.content.ClipboardManager for the other one. These are used in different ways and need to be separated.
Activity1
import android.content.ClipboardManager;
public class Activity1 extends ListActivity {
ThirdClass tc = new ThirdClass(this);
}
Activity2
import android.text.ClipboardManager; <--- different
public class Activity2 extends ListActivity {
ThirdClass tc = new ThirdClass(this);
}
ThirdClass
public class ThirdClass {
public ThirdClass (ListActivity la){
//do stuff
}
//other methods
}
In this third class I want there to be shared code that are used for both ListActivity classes. However, the third class needs to be able to tell whether it's working with Activity1 or Activity2 so that it can use the specific variables and methods that are defined within these classes. This can be done by casting the class name like this:
((Activity1) la).whatever
My question is, what's the easiest way to retrieve the class name Activity1 or Activity2 with code from the ListActivity variable "la" that has been passed down to ThirdClass?
The only way I've been able to figure out myself is by using getClass() and getName() and then using if statements as below.
String activity = la.getClass().getName();
if (activity == com.stuff.Activity1) {
//do stuff
}
But there has to be a better way so that I can directly cast the class name to anything using the "la" variable?
UPDATE
Using instanceof would result in a lot of duplicate code since I would have to write it up once for each instance as below. I'm hoping to avoid this.
if (la instanceof Activity1) {
((Activity1) la).whatever
}
if (la instanceof Activity2) {
((Activity2) la).whatever
}
Using an interface that contains the needed methods like Stefan suggested may be a good idea? I actually don't know much about interfaces so haven't considered this. I'll look into it.