gpt4 book ai didi

java - 在这种情况下如何参数化我的 Class 参数?

转载 作者:行者123 更新时间:2023-11-30 08:23:04 25 4
gpt4 key购买 nike

我有以下实用程序类和方法:

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);

请注意,我的“Instruction”类实现了一个名为“KSoapObjectParseable”的接口(interface)。

它工作正常,但在我的实用程序类 Eclipse 中警告:

Class is a raw type. References to generic type Class should be parameterized

正确的是,但是,如果我按如下方式参数化方法参数:

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>)

所以我的问题是,如何参数化我的方法参数并仍然能够通过传入实现 KSoapObjectParseable 的“MyClass,class”来调用它?

最佳答案

看起来您希望调用者传入一个是或扩展 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 中(因为它们传入了一个不可实例化的类)并重新抛出。

关于java - 在这种情况下如何参数化我的 Class 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com