希望你能帮助我:我有...
- 一个类名的字符串列表,称为
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 无法解析为类型
我的代码对于通用函数的单次调用运行完美:
Geography<ExampleClass> ExampleGeo;
read(ExampleClass.class, ExampleGeo);
任何想法我怎么能做到这一点?
更新:
感谢您提供有用的输入,但我仍然很难将它用于我的真实代码。所以这是一个非简单化的问题:
我在 shapefile-Data 中使用 shapefileLoader 做好了准备,对于 Shapefile 的每个功能,一个类 (GuadAgent) 使用预定义类 (PlantWind) 进行初始化。我的输入目录中有形状文件,其中包含它们的特征所代表的类的名称。我希望 Java 读取 shapefile 并创建相应的代理类。(代理也放置在上下文和地理中。)使用的类有:ShapefileLoader、Geography,其他类可以在同一网站上找到
这部分在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;
}
我怎样才能摆脱开关?虽然他们的数量是有限的,但有很多不同的代理......