java - Adding Getters/Setters to one Base class -
i got 1 thought, not able figure out how implement this.
public class basedomain<t>{ //generic methods goes here } public class domain1 extends basedomain<domain1>{ private int id; private string name; //only properties should present here } public class domain2 extends basedomain<domain2>{ private int id; private string name; //only properties should present here } in above scenario, can define generic methods in base class , can use in domain classes using generics. problem here want design mechanisim developer's have define properties in domain class(without getters/setters) somehow basedomain should provide getters/setters dynamically each domain.
any suggestion appreciated!
with reflection can that.
public class basedomain<t>{ public string getname() { return this.getclass().getfield("name").get(this); } public void setname(string value) { this.getclass().getfield("name").set(this, value); } } note this.getclass() refer runtime class of object, domain1 example. so, can access fields there, get/set values, etc.
you may need set access privileges if declare properties private or protected. they're public, should work.
as op mentioned, using getdeclaredfields() not force declare public fields, unfortunately have iterate through (or use map) access field specific name.
if field not present in object instance, you'll exception.
Comments
Post a Comment