inheritance - A few questions about Java Reflection -


i have parent class entity:

package incubator;  import java.lang.annotation.annotation; import java.lang.reflect.field;  public class entity {      private string gettablename() {         string result = null;         class<?> cl = getclass();         system.out.println(cl.getname());         (annotation : cl.getannotations()) {             if (a instanceof entitytable) {                 entitytable ent = (entitytable) a;                 result = ent.name();                 break;             }         }         return result;     }      private string getkeyname() {         string result = null;         class<?> cl = getclass();         system.out.println(cl.getname());         (field f : cl.getdeclaredfields()) {             (annotation : f.getannotations()) {                 if (a instanceof primarykey) {                     primarykey ann = (primarykey) a;                     result = ann.name();                 }             }         }         return result;     }      public entity get(int id) throws illegalaccessexception, instantiationexception {             system.out.println("select * "                     + gettablename() + " (" + getkeyname() + "=?);");             return getclass().newinstance();     }      public void delete() {             system.out.println("delete "                     + gettablename() + " (" + getkeyname() + "=?);");     }  } 

and child class child:

package incubator;  @entitytable(name="table") public class child extends entity {   @primarykey(name="tbl_pcode")   private int id;   @datafield(name="tbl_text")   public string text;   @datafield(name = "tbl_data")   public string data;    public child() {       id = 0;   } } 

all annotations like

package incubator;  import java.lang.annotation.elementtype; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.annotation.target;  @target(elementtype.type) @retention(retentionpolicy.runtime) public @interface entitytable {     string name(); } 

so, have question: there way make static method get(final int id) of class entity return instance of child? how can specify resulting type of child class[es] in parent class?

thanks wasting time me. best regards.

because of type erasure there no way actual type in static context @ runtime. you'd have explicitly declare class when calling method. using generic method this:

public static <t extends entity> t get(int id, class<t> clazz) {     return clazz.newinstance(); } 

i'm not sure if useful in case it's way if want go static.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -