Reputation: 1547
I'm working on a project in Java that will most likely support Android in the future. But from what I know, Android has different classes/APIs than default Java (for example, I don't think android has all of the AWT stuff). So what I'm wondering, is how can I write my code so that if it is running on Android, it will use the android APIs, and if it is on a desktop, it use the standard Java APIs. I have looked into conditional imports, but unlike C++, that doesn't exist in Java. So how is this kind of thing solved in Java.
Here is an example of what I would like to be able to do:
int[] i;
if(onAnroid)
{
i = androidFoo.bar();
} else {
i = javaFoo.bar();
}
EDIT: One thing I had thought of was using a Common class so I don't directly call the APIs. But What I was trying to figure out is how to call those classes of they aren't necessarily existent without the compiler complaining that the classes don't exist.
Upvotes: 2
Views: 166
Reputation: 86409
You can create architectural layers which are agnostic of any particular user-interface toolkit. If these need to interact with the user interface, they can do so through interface types.
Atop those layers, you can create multiple presentation layers with different toolkits.
Porting software to new user interfaces is common. Separating architectural layers from the beginning can cost little. De-tangling a monolith later can be expensive, sometimes to the point that it is economically infeasible for a company. Whether a requirement to port is certain, possible or unknown, it can be a good practice to separate architectural layers early.
Upvotes: 3
Reputation: 48272
Regarding not-necessarily existing classes you can call like this:
try {
MyObject o = (MyObject)Class.forName("org.me.MyObject").newInstance();
} catch(ClassNotFoundException x) {
// Here you know class does not exist
}
Actually, you should do better than this but I don't remember. But anyway similar to this.
Upvotes: 1
Reputation: 2785
You will have to separate your code, but not like this. Your classes need to be designed to separate the code that is platform dependent from the code it isn't. You should focus on keep the core logic of the application in one layer and render the objects on the screen in another layer.
Upvotes: 2
Reputation: 251
Dependency Injection can probably serve your needs. There are several Frameworks out there: http://en.wikipedia.org/wiki/Dependency_injection#Frameworks_that_support_dependency_injection
Upvotes: 0