【发布时间】:2014-10-09 22:43:10
【问题描述】:
希望您能帮我解决这个问题: 我有...
- 一个名为
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) 进行初始化。我的输入目录中有 shapefile,其中包含它们的特征所代表的类的名称。我希望 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;
}
如何摆脱开关?虽然他们的数量是有限的,但是有很多不同的代理......
【问题讨论】:
-
由于类型擦除,这可能是不可能的。在运行时,只存在一种类型
Geography,所有出现的T都替换为其上限,在您的情况下为Object。
标签: java generics shapefile geotools repast-simphony