是否有一些库或生成器可用于从单个模板生成多个模板化java类?
显然,Java确实有一个泛型实现,但由于它使用了类型擦除,因此在很多情况下它不够用。
例如,如果我想制作一个像这样的自增长数组:
class EasyArray {
T[] backingarray;
}
(其中T是基本类型),那么这是不可能的。
对于任何需要数组的东西都是如此,例如高性能模板化矩阵和矢量类。
应该可以编写一个代码生成器,它接受一个模板化的类并为不同的类型生成多个实例,例如'double'和'float','int'和'String'。是否存在已经存在的东西?
编辑:请注意,使用Object数组并不是我想要的,因为它不再是基元数组。基元数组非常快,并且仅使用sizeof(原始)*数组长度的空间。对象数组是一个指针/引用数组,指向Double对象或类似对象,它们可以分散在内存中的所有位置,需要垃圾收集,分配,并暗示双重间接访问。
EDIT3:
以下是显示原始数据和盒装数组之间性能差异的代码:
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();
结果:
double[] array: 148 ms
Double[] array: 4614 ms
甚至没有关闭!
答案 0 :(得分:0)
提出以下草案的方式:
我们使用占位符类型TemplateArgOne
创建一个类,并添加一个用于促进解析的注释:
@GenerateFrom(EndlessArray.class)
public class EndlessArray {
TemplateArgOne[] values;
int size = 0;
int capacity;
public EndlessArray() {
capacity = 10;
values = new TemplateArgOne[capacity];
}
public void reserve(int newcapacity ) {
if( newcapacity > capacity ) {
TemplateArgOne[] newvalues = new TemplateArgOne[newcapacity];
for( int i = 0; i < size; i++ ) {
newvalues[i] = values[i];
}
values = newvalues;
capacity = newcapacity;
}
}
public void add( TemplateArgOne value ) {
if( size >= capacity - 1 ) {
reserve( capacity * 2);
}
values[size] = value;
}
public void set( int i, TemplateArgOne value ) {
values[i] = value;
}
public TemplateArgOne get( int i ) {
return values[i];
}
}
我们将TemplateArgOne定义为一个空类,所以上面的代码编译得很好,可以在Eclipse中编译它没有任何问题:
public class TemplateArgOne {
}
现在,我们创建一个新类来实例化模板类,并添加一些注释来告诉生成器我们想要实例化哪个类,以及我们想要TemplateArgOne
的类型:
@GenerateFrom(root.javalanguage.realtemplates.EndlessArray.class)
@GenerateArg(from=TemplateArgOne.class,to=double.class)
public class EndlessArrayDouble {
}
然后我们运行生成器,传入源代码的目录,以及实例化类的名称,即EndlessArrayDouble
:
public static void main(String[] args ) throws Exception {
new RealTemplateGenerator().go("/data/dev/machinelearning/MlPrototyping", EndlessArrayDouble.class);
}
并且presto!当我们转到EndlessArrayDouble类时,它已经填充了我们的代码! :
package root.javalanguage.realtemplates;
import root.javalanguage.realtemplates.RealTemplateGenerator.*;
@GenerateArg(from=TemplateArgOne.class,to=double.class)
@GenerateFrom(root.javalanguage.realtemplates.EndlessArray.class)
public class EndlessArrayDouble {
double[] values;
int size = 0;
int capacity;
public EndlessArrayDouble() {
capacity = 10;
values = new double[capacity];
}
public void reserve(int newcapacity ) {
if( newcapacity > capacity ) {
double[] newvalues = new double[newcapacity];
for( int i = 0; i < size; i++ ) {
newvalues[i] = values[i];
}
values = newvalues;
capacity = newcapacity;
}
}
public void add( double value ) {
if( size >= capacity - 1 ) {
reserve( capacity * 2);
}
values[size] = value;
}
public void set( int i, double value ) {
values[i] = value;
}
public double get( int i ) {
return values[i];
}
}
请注意,如果多次运行它而不修改模板类,则不会修改实例化类java文件,即它不会在Eclipse中触发冗余文件重新加载。
生成器代码:
//Copyright Hugh Perkins 2012, hughperkins -at- gmail
//
//This Source Code Form is subject to the terms of the Mozilla Public License,
//v. 2.0. If a copy of the MPL was not distributed with this file, You can
//obtain one at http://mozilla.org/MPL/2.0/.
package root.javalanguage.realtemplates;
import java.lang.annotation.*;
import java.util.*;
public class RealTemplateGenerator {
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface GenerateFrom {
Class<?> value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface GenerateArg {
Class<?> from();
Class<?> to();
}
public final static BufferedReader newBufferedReader(String filepath ) throws Exception {
FileInputStream fileInputStream = new FileInputStream( filepath );
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader;
}
public final static BufferedWriter newBufferedWriter( String filepath ) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(filepath);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
return bufferedWriter;
}
public final static ArrayList<String> readFileAsLines(String filepath ) throws Exception {
ArrayList<String> lines = new ArrayList<String>(40000);
BufferedReader bufferedReader = newBufferedReader(filepath);
String line = bufferedReader.readLine();
int numlines = 0;
while( line != null ) {
lines.add(line.substring(0, line.length() ));
line = bufferedReader.readLine();
numlines++;
}
bufferedReader.close();
return lines;
}
public final static void writeFileFromLines( String filepath, ArrayList<String> lines ) throws Exception {
BufferedWriter bufferedWriter = newBufferedWriter(filepath);
for( String line : lines ) {
bufferedWriter.write(line + "\n");
}
bufferedWriter.close();
}
void go( String sourcedirectory, Class<?> targetclass ) throws Exception {
String targetclassfilepath = sourcedirectory + "/" + targetclass.getCanonicalName().replace(".","/") + ".java";
ArrayList<String> initialLines = FileHelper.readFileAsLines(targetclassfilepath);
String fromclassname = "";
HashMap<String,String> argOldToNew = new HashMap<String, String>();
ArrayList<String> generatelines = new ArrayList<String>();
for( String line : initialLines ) {
if( line.startsWith("@GenerateFrom")){
fromclassname = line.split("\\(")[1].split("\\.class")[0];
}
if( line.startsWith("@GenerateArg")) {
String fromclass= line.split("from=")[1].split("\\.")[0];
String toclass = line.split("to=")[1].split("\\.")[0];
argOldToNew.put(fromclass,toclass);
generatelines.add(line);
}
}
Class<?> targettype = this.getClass().forName(fromclassname);
String fromclassfilepath = sourcedirectory + "/" + targettype.getCanonicalName().replace(".","/") + ".java";
ArrayList<String> templateLines = FileHelper.readFileAsLines(fromclassfilepath );
ArrayList<String> generatedLines = new ArrayList<String>();
for( int i = 0; i < templateLines.size(); i++ ){
String line = templateLines.get(i);
if( !line.startsWith("@GenerateFrom") && !line.startsWith("@GenerateArg")) {
for( String oldarg : argOldToNew.keySet() ) {
line = line.replace(oldarg, argOldToNew.get(oldarg));
}
line = line.replace(targettype.getSimpleName(), targetclass.getSimpleName());
} else if( line.startsWith("@GenerateFrom") ) {
for( String generateline : generatelines ) {
generatedLines.add(generateline);
}
}
generatedLines.add(line);
}
boolean isModified = false;
if( initialLines.size() != generatedLines.size() ) {
isModified = true;
} else {
for(int i = 0; i < initialLines.size(); i++ ) {
if( !initialLines.get(i).equals(generatedLines.get(i))) {
isModified = true;
break;
}
}
}
if( isModified ) {
FileHelper.writeFileFromLines(targetclassfilepath, generatedLines);
System.out.println("Generated " + targetclassfilepath );
} else {
System.out.println("No change to " + targetclassfilepath );
}
}
public static void main(String[] args ) throws Exception {
new RealTemplateGenerator().go("/data/dev/machinelearning/MlPrototyping", EndlessArrayDouble.class);
}
}