Java Generic type identification -
this class structure.
public class node<t> { private t value; public node(t val) { this.value = val; } public t evaluate() { return value; }; }
t can integer
, double
, date
, long
or string
.
now, there anyway can know type t is? thanks.
you can invoke getclass()
method on generic variable , find out class. generics erased @ run-time, unbounded generic nothing java.lang.object
. can invoke method supported object
class on generic variable
at run-time, getclass()
on generic object return actual class
used substitute generic
for example
public class node<t> { private t value; public node(t val) { class<?> clazz = val.getclass(); checktype(clazz); this.value = val; } public t evaluate() { return value; }; private void checktype(class<?> c) { if(c.getname().equals(integer.class.getname())) { //... } } }
Comments
Post a Comment