将已经转换的对象返回到具体类类型

时间:2015-08-18 19:37:50

标签: java generics

请参阅以下方法。 有没有办法以通用方式转换创建的对象并将已经转换的对象返回到具体的类类型,因此用户不必自己投射它?

public static  Object getObject(String xmlString, String fullyQualifiedClassName) throws Exception {

        StringReader reader = new StringReader(xmlString);
        UploadDocument doc = (UploadDocument) unmarshaller.unmarshal(reader);

        Class<?> clazz = (Class<?>) Class.forName(fullyQualifiedClassName);

        UploadResult result = DataUploaderUtil.createObject(doc);

        if (result != null) {
              Object uploadObject = result.getUploadObject();
              if (uploadObject != null && clazz.isInstance(uploadObject)) {
                    return uploadObject;
              }
        }
        return null;

  }

1 个答案:

答案 0 :(得分:1)

是的,假设调用者具有类对象(如果他们能够手动编译,他们会这样做):

public static <T> T getObject(String xmlString, Class<T> clazz) throws Exception {
    ...
    return (T) uploadObject;
}

调用:

Foo f = getObject(someXml, Foo.class);