Search code examples
javaandroidbuild-process

Dynamic (compile-time generated) Java package name


I am developing a generic Android game engine that will be used in many of my Android apps as the base system. The problem is that in all of my Java files I currently have to hardcode the package name like this:

package com.example.mygameengine;

But because I want to use the code of my generic game engine in many different apps, I need to find a way to specify the package name for the Java files at compile time because I do not want to keep several copies of my Java sources just because of differences in the package name. I want to have one central source tree and the package name should be dynamically changeable depending on the app I'm about to compile.

So is there a way to do something like this:

package $(PACKAGE_NAME)

In the Java sources where $(PACKAGE_NAME) is to be substituted with the real package name at compile time? Maybe javac has an option that allows me to specify a package name for the file it is passed instead of taking it from the file itself? Note that I'm not using Eclipse but barebones command line tools like ant and make.

EDIT: I do not understand why this is tagged as a duplicate. I've asked a fundamental question about whether the "package" directive in the Java language requires a hard-coded string argument in the source code or whether it is also possible to set this package name at compile time using a compiler directive. That's quite a different question than the one that has been linked here as the presumedly "original" question which is much more closely tied to the Android build system. My question is about the fundamentals of the Java language, not about the Android build system.


Solution

  • You can't. And that's not the proper approach to code reuse.

    Simply package your commonly used code in a jar and include that jar in every project you want (in Android you do that by adding the class to the classpath, and then marking it as exported in the "Order & Export" tab)