經過相當多的谷歌搜索和嘗試失敗後,我已經解決了以下問題。我有一個Util
類,如果我通過Class
,則會得到一個json字符串。我現在使用Jackson Library來獲取json表示。
public class Util {
public static String toJsonString(Class<?> entity)
{
ObjectMapper mapper = new ObjectMapper();
String json = "";
try {
String toolItemMode = "";
List<Class<?>> interfaceList = Arrays.asList(entity.getInterfaces());
if (interfaceList.contains(IConnectableObject.class))
{
toolItemMode = "both";
}
else if (interfaceList.contains(IConnectionSource.class))
{
toolItemMode = "source";
}
else if (interfaceList.contains(IConnectionSink.class))
{
toolItemMode = "sink";
}
json = mapper.writeValueAsString(entity.newInstance());
ObjectNode objectNode = (ObjectNode) mapper.readTree(json);
objectNode.put("mode", toolItemMode);
json = objectNode.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return json;
}
}
然後在控制器方法我做這種方式...
.....
Reflections reflections = new Reflections("com.obsm.myapp.model.configuration");
Set<Class<? extends IConfigurationEntity>> classes = reflections.getSubTypesOf(IConfigurationEntity.class);
Map<String, String> toolBox = new HashMap<String, String>();
for (Class<? extends IConfigurationEntity> configItem : classes)
{
toolBox.put(configItem.getSimpleName(), Util.toJsonString(configItem));
}
model.addAttribute("toolBox", toolBox);
.....
如果有人有什麼更好的主意,我敢肯定,你們許多人,我渴望瞭解它們。希望這可以幫助別人。 :-)