これで私を助けてくれることを願っています:私は...
- と呼ばれるクラス名の文字列リスト
classNameList
- ジェネリック クラス
Geography<T>
- 静的ジェネリック メソッド
<T> void read(Class<T> cl, Geography<T> geo)
文字列クラス名リストをループして、これらのクラスごとにジェネリック メソッドを呼び出したいと考えています。
私が試したことは明らかにうまくいきませんでした:
for (int i = 0; i < classNameList.length; i++) {
Class<?> myClass = Class.forName(classNameList[i].getName());
Geography<myClass.newInstance()> geo;
read(myClass, geo);
}
エラー: myClass.newInstance を型に解決できません
私のコードは、ジェネリック関数の 1 回の呼び出しで完全に実行されます。
Geography<ExampleClass> ExampleGeo;
read(ExampleClass.class, ExampleGeo);
これを行う方法はありますか?
アップデート:
有益な情報をありがとうございます。それでも、実際のコードに採用するのは難しいです。したがって、これは単純化されていない問題です。
ShapefileLoader を使用して shapefile-Data を準備します。Shapefile の各機能について、クラス (GuadAgent) が事前定義されたクラス (PlantWind) で初期化されます。入力ディレクトリにシェープファイルがあり、それらの機能が表すクラスの名前が含まれています。Java がシェープファイルを読み込んで、それぞれのエージェント クラスを作成するようにします。(エージェントはコンテキストと地理にも配置されます。) 使用されるクラスは次のとおりです: ShapefileLoader、Geography、他のクラスは同じ Web サイトにあります。
この部分は main-method にあります。
Geography<GuadAgent> guadGeography = GeographyFactoryFinder.createGeographyFactory(null).createGeography("guadGeography", context, new GeographyParameters<GuadAgent>());
Context<GuadAgent> context = new DefaultContext<GuadAgent>();
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".shp"); // return .shp files
}
};
String shapefileDir = System.getProperty("user.dir")+"\\input\\shp\\";
File folder = new File(shapefileDir);
File[] listOfFiles = folder.listFiles(filter);
for (File classFile : listOfFiles) {
try {
readForName(classFile,context,guadGeography);
} catch (ClassNotFoundException | MalformedURLException
| FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
名前を読み取る静的メソッド:
static <T> void readForName(File classFile, Context<GuadAgent> context,Geography<GuadAgent> guadGeography) throws ClassNotFoundException, MalformedURLException, FileNotFoundException {
String shapefileDir = System.getProperty("user.dir")+"\\input\\shp\\";
String className = classFile.getName().split("\\.(?=[^\\.]+$)")[0];
File shapefile = null;
shapefile = new File(shapefileDir+classFile.getName());
if (!shapefile.exists()) {
throw new FileNotFoundException("Could not find the given shapefile: " + shapefile.getAbsolutePath());
}
switch (className) {
case "PlantWind":
ShapefileLoader<PlantWind> PlantWindLoader = new ShapefileLoader<PlantWind>(PlantWind.class,shapefile.toURI().toURL() , guadGeography, context);
PlantWindLoader.load();
PlantWindLoader.close();
System.out.println(context.getObjects(PlantWind.class).size());
break;
// Todo Add other Agent types
default:
break;
}
どうすればスイッチを外すことができますか? それらの数は有限ですが、非常に多くの異なるエージェントがいます...