dleerob
dleerob

Reputation: 5371

How do I parameterize my Class parameter in this case?

I have the following Utility class and method:

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

}

I then call this method as follows:

Instruction instruction = (Instruction)KSoapUtility.parseObject(instructionSoapObject, Instruction.class);

Note that my "Instruction" class implements an interface called "KSoapObjectParseable".

It works fine, but in my Utility class Eclipse warns:

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

Correctly so, however, if I parameterize the method argument as follows:

Class<KSoapObjectParseable> clazz

Then the following call wont compile:

Instruction instruction = (Instruction)KSoapUtility.parseObject(instructionSoapObject, Instruction.class);

giving the error:

The method parseObject(SoapObject, Class<KSoapObjectParseable>) in the type KSoapUtility is not applicable for the arguments (SoapObject, Class<Instruction>)

So my question is, how do you parameterize my method argument and still be able to call it by passing in "MyClass,class" that implements KSoapObjectParseable ?

Upvotes: 2

Views: 49

Answers (1)

It looks like you expect the caller to be passing in a class that is or extends KSoapObjectParseable, so try this (with the necessary try/catch logic):

public static <T extends KSoapObjectParseable> T parseObject(SoapObject soapObject, Class<T> clazz) {
    T obj = clazz.newInstance();
    // stuff
    return obj;
}

Note also that since you're passing in that SoapObject, it would be better to make this an instance method there if you control that class.

Finally, don't ever just swallow exceptions like you're doing here, and don't catch Exception; in fact, most of the time, printing the stack trace isn't even helpful (because the caller will want to log it using the appropriate logging system for the application). Instead, wrap that InstantiationException into an IllegalArgumentException (because they passed in an uninstantiable class) and rethrow.

Upvotes: 3

Related Questions