1

In Java, is it possible to declare a new class field after the object has been constructed?

I remember being able to do so in Python using the "self" prefix:

def setMember():
  this.member = value

But, perhaps that is one of the "benefits" of not requiring pre-declared variables?

I've done a little searching around but I haven't found anything that even references the subject. Perhaps I'm not using the right key words.

AntumDeluge
  • 490
  • 1
  • 5
  • 13
  • 1
    No. Python and Java are different in *many* ways. This is one of them. – Sinkingpoint Apr 02 '15 at 00:29
  • So Java reflection is only for introspection? We can't modify the classes on the go? – Dunes Buggy Apr 02 '15 at 00:30
  • @iRaviiVooda Modification at that level would require all sorts of trickery that goes along with a compiled language. E.g. having to modify the allocated memory of every instance of that class. – Sinkingpoint Apr 02 '15 at 00:31
  • What are you trying to accomplish? There are usually other equivalents. – chrylis -cautiouslyoptimistic- Apr 02 '15 at 00:32
  • Although not answering your question specifically, this is question good background reading on a closely related topic: https://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages – Erwin Bolwidt Apr 02 '15 at 01:38
  • I know you said Java but have you considered using groovy and metaClass? Sounds like that would solve your problem: http://docs.groovy-lang.org/latest/html/api/groovy/lang/MetaClass.html – Jason McD Apr 02 '15 at 05:10
  • Thank you all very much. This has been informative. – AntumDeluge Apr 13 '15 at 11:34

0 Answers0