java - Create Fields and methods dynamically -
i want add new fields(variables) , encapsulating methods given class. example: class name student has no fields below:
public class student implements serializable{ } then in application instance created;
student s=new student(); i want add new methods not exist student class @ run time.for example: want add field called studentname, , getstudentname() , setstudentname() methods.
then @ run time student object this;
public class student implements serializable{ private string studentname; public void setstudentname(..){} public string getstudnetname(){return ...;} } in application objects written text file , objects of same type not have variables. therefore, want add required fields save memory.
any way there way this? sample code or link?
edit: or else can create class either , create instances not exists ?
edit 2: of answered , got many info , ideas. , changed way better path suggestions well
why not create hashmap of values? more efficient, , has flexibility you're looking for.
public class student { private hashmap<string, string> values; public student() { this.values = new hashmap<string, string>(); } public void addvalue(string name, string value) { values.put(name, value); } public string getvalue(string name) { return values.get(name); } } why hashmap?
you said objects may have differing values, , you'll defining new methods , attributes string. well.. achieve functionality without horrible bytecode manipulation. example:
string attrname = "name"; string attrvalue = "jim"; student stu = new student(); stu.addvalue(attrname, attrvalue); at moment, you've got 1 value in hashmap. overheard have face hashmap object itself, , 2 methods, frankly fair trade off far tidier solution.
Comments
Post a Comment