3

1 つのテンプレートから複数のテンプレート化された Java クラスを生成するために使用できるライブラリまたはジェネレータはありますか?

明らかに、Java 自体にはジェネリックスの実装がありますが、型消去を使用するため、十分とは言えない状況がたくさんあります。

たとえば、次のような自己成長配列を作成したい場合:

 class EasyArray {
      T[] backingarray;
 }

(ここで、T はプリミティブ型です)、これは不可能です。

これは、高性能のテンプレート化された行列やベクトル クラスなど、配列を必要とするものすべてに当てはまります。

テンプレート化されたクラスを取り、「double」と「float」と「int」と「String」など、さまざまなタイプの複数のインスタンス化を生成するコード ジェネレーターを作成することはおそらく可能です。これを行うものはすでに存在しますか?

編集:オブジェクトの配列を使用することは、私が探しているものではないことに注意してください。これは、プリミティブの配列ではなくなったためです。プリミティブの配列は非常に高速で、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 に答える