Is there some library or generator that I can use to generate multiple templated java classes from a single template?
Obviously Java does have a generics implementation itself, but since it uses type-erasure, there are lots of situations where it is less than adequate.
For example, if I want to make a self-growing array like this:
class EasyArray {
T[] backingarray;
}
(where T is a primitive type), then this isn’t possible.
This is true for anything which needs an array, for example high-performance templated matrix and vector classes.
It should probably be possible to write a code generator which takes a templated class and generates multiple instantiations, for different types, eg for ‘double’ and ‘float’ and ‘int’ and ‘String’. Is there something that already exists that does this?
Edit: note that using an array of Object is not what I’m looking for, since it’s no longer an array of primitives. An array of primitives is very fast, and uses only as much space a sizeof(primitive) * length-of-array. An array of object is an array of pointers/references, that points to Double objects, or similar, which could be scattered all over the place in memory, require garbage collection, allocation, and imply a double-indirection for access.
Edit3:
Here is code to show the difference in performance between primitive and boxed arrays:
int N = 10*1000*1000;
double[]primArray = new double[N];
for( int i = 0; i < N; i++ ) {
primArray[i] = 123.0;
}
Object[] objArray = new Double[N];
for( int i = 0; i < N; i++ ) {
objArray[i] = 123.0;
}
tic();
primArray = new double[N];
for( int i = 0; i < N; i++ ) {
primArray[i] = 123.0;
}
toc();
tic();
objArray = new Double[N];
for( int i = 0; i < N; i++ ) {
objArray[i] = 123.0;
}
toc();
Results:
double[] array: 148 ms
Double[] array: 4614 ms
Not even close!
Came up with the following draft way of doing this:
We create a class, using the placeholder type
TemplateArgOne, and add an annotation that is used to facilitate parsing:We define TemplateArgOne as an empty class, so the above code compiles just fine, can edit it with no problems in Eclipse:
Now, we create a new class to instantiate the template class, and we add a couple of annotations to tell the generator which class we want to instantiate, and what type we want for
TemplateArgOne:Then we run the generator, passing in the directory of our source code, and the name of the instantiation class, ie
EndlessArrayDouble:And presto! When we go to the EndlessArrayDouble class, it’s been populated with our code! :
Note that if you run it multiple times, without modifying the template class, then the instantiation class java file will not be modified, ie it wont trigger a redundant file reload in Eclipse.
The generator code: