Read annotation of generic class Java -
i had idea use dao class (dao.java):
class dao <model extends abstractmodel> { public string geturl() { return model.class.getannotation(mypath.class).url(); } }
and model (account.java):
@mypath(url = "blabla") class account extends abstractmodel { ... }
but problem in case if run
@test public void testdaourl() { dao<account> dao = new dao<account>(); dao.geturl(); }
model.class seems abstractmodel , not account. is there work around mypath annotation dao (without giving instance of account.class)?
thanks in advance idea!
ps: mypath-annotation:
@retention(runtime) @target(type) @interface mypath { public string url(); }
yes, there solution, it's uglier passing class
argument dao
constructor , more prone error.
this trick known type token. i've seen used in deserialization libraries (like gson or jackson json).
class dao<model extends abstractmodel> { private final class<?> typeargument; public dao() { type superclass = getclass().getgenericsuperclass(); parameterizedtype parameterized = (parameterizedtype) superclass; // nested generic types, becomes little more complicated typeargument = (class<?>) parameterized.getactualtypearguments()[0]; } public string geturl() { return typeargument.getannotation(mypath.class).url(); } }
and used so
new dao<account>(){}.geturl()
so, when creating dao
instance, actually, instead, create dao
subclass instance. way instance of parameterized subtype of dao
, ie. like
class anonymousdao extends dao<account> {}
and parameterized type can extracted , used.
Comments
Post a Comment