java - Instantiate Parameterized Type class with Class<?> variable -
(note: have searched multiple questions on in similar domain, never encountered answer specific idea).
consider if have class or enum foo
each instance has class<?> type
field:
public enum foo { (integer.class), b (double.class), c (string.class); public final class<?> type; foo(class<?> type) { this.type = type; } }
then have generic class bar<v>
:
public class bar<v> { private v value; // default constructor public bar() {} // getter public v getvalue(){ return value; } // setter public void setvalue(v value){ this.value = value; } }
is possible instantiate instance of bar
type class<?> type
field of given foo
without knowing specific type of foo.type
? instance, call in either static method, or kind of factory method.
edit:
to specify function of bar: bar wraps around value simple getter/setter, , has consistent interface, unknown type. benefit of idea create instances of bar based off of instance of foo. instance, use value of foo.a.type
(which integer.class
) instantiate bar<integer>
without knowing ahead of time foo.a.type
has value of integer.class
.
given constructor in bar
class, in order instantiate new bar<v>
object, need object of type v
.
so, problem translates instantiating object of type class<v>
. more specifically, assuming existing foo
object , gettype()
method in foo
class, like:
foo foo = ... // existing foo object class<v> type = foo.gettype(); v value = instantiate(type); // todo: implement instatiate() bar<v> bar = new bar(value);
the trick implementation of instantiate()
method. if class<v>
has no-args constructor, can call
v value = type.newinstance();
not classes have default constructor, though, there no generic solution cases.
Comments
Post a Comment