我有以下Utility类和方法:
public class KSoapUtility {
public static KSoapObjectParseable parseObject (SoapObject soapObject, Class clazz) {
KSoapObjectParseable obj = null;
try {
obj = (KSoapObjectParseable)clazz.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
if (obj != null) {
String[] propertyNames = obj.getPropertyNames();
for (String propertyName: propertyNames) {
obj.setProperty(propertyName, soapObject.getPropertyAsString(propertyName));
}
}
return obj;
}
}
然后我按如下方式调用此方法:
Instruction instruction = (Instruction)KSoapUtility.parseObject(instructionSoapObject, Instruction.class);
请注意我的"指令" class实现了一个名为" KSoapObjectParseable"。
的接口它运行正常,但在我的Utility类Eclipse中警告:
Class是原始类型。对泛型类的引用应该参数化
正确地说,如果我按如下方式参数化方法参数:
Class<KSoapObjectParseable> clazz
然后以下调用不会编译:
Instruction instruction = (Instruction)KSoapUtility.parseObject(instructionSoapObject, Instruction.class);
给出错误:
The method parseObject(SoapObject, Class<KSoapObjectParseable>) in the type KSoapUtility is not applicable for the arguments (SoapObject, Class<Instruction>)
所以我的问题是,你如何参数化我的方法参数,并且仍然可以通过传入&#34; MyClass,class&#34;来调用它。实现KSoapObjectParseable?
答案 0 :(得分:3)
看起来你希望调用者在一个或者扩展KSoapObjectParseable
的类中传递,所以试试这个(使用必要的try / catch逻辑):
public static <T extends KSoapObjectParseable> T parseObject(SoapObject soapObject, Class<T> clazz) {
T obj = clazz.newInstance();
// stuff
return obj;
}
另请注意,由于您传入SoapObject
,如果您控制该类,最好将其作为实例方法。
最后,不要只是吞下你在这里做的异常,而不要抓住Exception
;事实上,大多数情况下,打印堆栈跟踪甚至没有帮助(因为调用者希望使用适当的应用程序日志系统来记录它)。相反,将InstantiationException
包装到IllegalArgumentException
中(因为它们传入了一个不可实例化的类)并重新抛出。