java - How do I parameterize my Class parameter in this case? -


i have following utility class , 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();         (string propertyname: propertynames) {             obj.setproperty(propertyname, soapobject.getpropertyasstring(propertyname));         }     }     return obj; } 

}

i call method follows:

instruction instruction = (instruction)ksoaputility.parseobject(instructionsoapobject, instruction.class); 

note "instruction" class implements interface called "ksoapobjectparseable".

it works fine, in utility class eclipse warns:

class raw type. references generic type class should parameterized

correctly so, however, if parameterize method argument follows:

class<ksoapobjectparseable> clazz 

then following call wont compile:

instruction instruction = (instruction)ksoaputility.parseobject(instructionsoapobject, instruction.class); 

giving error:

the method parseobject(soapobject, class<ksoapobjectparseable>) in type ksoaputility not applicable arguments (soapobject, class<instruction>) 

so question is, how parameterize method argument , still able call passing in "myclass,class" implements ksoapobjectparseable ?

it looks expect caller passing in class or extends ksoapobjectparseable, try (with necessary try/catch logic):

public static <t extends ksoapobjectparseable> t parseobject(soapobject soapobject, class<t> clazz) {     t obj = clazz.newinstance();     // stuff     return obj; } 

note since you're passing in soapobject, better make instance method there if control class.

finally, don't ever swallow exceptions you're doing here, , don't catch exception; in fact, of time, printing stack trace isn't helpful (because caller want log using appropriate logging system application). instead, wrap instantiationexception illegalargumentexception (because passed in uninstantiable class) , rethrow.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -