3

是否有一些库或生成器可用于从单个模板生成多个模板化 java 类?

显然,Java 本身确实有一个泛型实现,但是由于它使用类型擦除,所以在很多情况下它还不够。

例如,如果我想制作一个像这样的自增长数组:

 class EasyArray {
      T[] backingarray;
 }

(其中 T 是原始类型),那么这是不可能的。

对于任何需要数组的东西都是如此,例如高性能模板化矩阵和向量类。

应该可以编写一个代码生成器,它接受一个模板类并为不同的类型生成多个实例,例如“double”和“float”以及“int”和“String”。有没有已经存在的东西可以做到这一点?

编辑:请注意,使用 Object 数组不是我想要的,因为它不再是原语数组。基元数组非常快,并且只使用 sizeof(primitive) * length-of-array 的空间。对象数组是指向 Double 对象或类似对象的指针/引用数组,它们可能分散在内存中的各处,需要垃圾收集、分配,并暗示访问的双重间接。

编辑3:

下面是显示原始数组和盒装数组之间性能差异的代码:

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

差远了!

4

1 回答 1

0

提出了以下草案方式:

我们创建一个类,使用占位符 type 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);
}

快!当我们转到 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);
    }
}
于 2012-10-13T09:31:49.870 回答