You could make your server project a sub-project of your client project, meaning that your server has access to all the classes the client needs, plus some extras.
Alternatively, you can create a JAR containing shared classes, and install this to your local (or remote if you have access) maven repository, using mvn install
(docs here: https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html)
For the actual transfer of data, you could serialize your objects using the Serializable
interface, however there are many issues with this approach:
- Fragile to class changes - if you change your class, old objects will likely break unless you manually manage this
- Java-only - you will not be able to, for example, write your client in C++ and your server in Java, if you ever decide to do something similar.
- Framework incompatibility - many popular frameworks work primarily with other formats, and cannot guarantee compatibility.
Instead, you can use:
- JSONs - Using Jackson Databind, or Google Gson libraries, they are flexible, powerful and standardised
- XML - Similar to JSONs, with some subtle differences
- Google Protobuf - Also has some limitations but very underrated for resource-constrained environments.
- Custom String Format - implement your own
toDataString()
and fromDataString()
methods. This is only really feasible for small classes, as there are many issues with Unicode, escape characters, encodings etc that most libraries hide from you. This is more risky than other methods.
In general, I would reccomend JSON unless you have a good reason to do otherwise. I personally use Jackson, here is a link to a tutorial: http://tutorials.jenkov.com/java-json/jackson-objectmapper.html