java - Generic type as method argument -
this question has answer here:
i create method can accept object type parameter, can use instantiate object.
for example, pass in type string
method, , within method body, do
list<string> l = new arraylist<string>(); string s = new string("abc");
how go doing this?
edit:
how have java method return generic list of type? answer first part of question.
as followup, create instance of passed in type within method body in second line in code snippet above?
there not mechanism in order generics. have use reflection that.
public <t> t instantiator(class<t> c){ if (c != null){ try { return (t) c.getconstructor().newinstance(); } catch (exception e) { e.printstacktrace(); } } return null; }
however reflections may fail if not used carefully. method wrote works fine if class has constructor no parameters. example, instantiator(string.class);
, instantiator(exception.class);
work since have empty constructor instantiator(integer.class)
won't run.
Comments
Post a Comment