问题
I would like to make a single Android app for multiple Android versions (possibly every one of them) My problem is that I want to check what is the version of Android the app is currently running on, and dynamically load a class which is version dependent. This part should be ok.
I just wonder how I can achieve that without compilation errors in my Eclipse project. I mean, the project is configured for a particular target (1.5, 2.1 ...), so if a class in my project is not compatible wich the selected target, it will result in errors.
Is there a way to export this classes even if they are not fit for the platform (I thought about a separated lib, but then again : how to compile theses classes into a lib without compilation pbs?) ? This should be ok since they won't be loaded until I ask them to after having checked Android version.
Thanks!
回答1:
You could use Class.forName
to load different classes depending on different conditions:
public interface MyType {}
public class MyTypeOn15 implements MyType {}
public class MyTypeOn16 implements MyType {}
public class MyTypeOn20 implements MyType {}
// ...
and somewhere else in your code:
MyType myType = null;
if (getActualTarget().equals("1.5") {
myType = Class.forName("MyTypeOn15").newInstance();
} else if (getActualTarget().equals("1.6") {
myType = Class.forName("MyTypeOn16").newInstance();
} // ...
Note that you need an accessible empty constructor in your implementations. And getActualTarget()
is your magic method that's returns the target as a String identifier...
回答2:
If you compile you project with latest target, i.e. 2.2 it still will run on 1.5.
来源:https://stackoverflow.com/questions/3530721/dynamic-class-loading-to-target-multiple-android-versions