0

Is there a way of defining a class "on the fly"-- that is, instantiating an object without an explicit declaration of a class?

What i'm looking for is instantiating an object, using the constructor of Object maybe(?), and defining some members (2 literal variables) while doing that.

I need an object-- and one object of that type only-- of 2 literals as members. I don't want to define a class to do that. And, as far as i know, Java doesn't have some type like struct to do that.

I don't think Java does this-- but still.

Thanks in advance.

Note: i've seen Does Java support structs? and Struct like objects in Java.

Community
  • 1
  • 1
Roam
  • 4,831
  • 9
  • 43
  • 72
  • 2
    Nope. Put them into an enum with one member; the extra boilerplate is three lines. See http://stackoverflow.com/questions/427902 – yshavit Nov 12 '13 at 04:26
  • There are no structs in java. Perhaps what you want is just an array of size 2, or an `enum`. – Steve P. Nov 12 '13 at 04:27
  • @yshavit this is fine. thx. – Roam Nov 12 '13 at 04:29
  • @Steve P. array wd do technically, but doesn't look crafty. thx just the same. – Roam Nov 12 '13 at 04:31
  • FYI, the inability to do this succinctly is one reason why you'll see Java spin-offs like Groovy and Scala. – Paul Draper Nov 12 '13 at 04:34
  • @Roam I understand where you're coming from, but it doesn't have to be "crafty." An array of size 2 is probably the best way to go here. An `enum` would make sense if you wanted to restrict the values that your "object" can take, but otherwise I would just go with an array...If you want to be crafty look into other languages, java is not good for this sort of thing. – Steve P. Nov 12 '13 at 04:35
  • @Paul Draper - dont know abt Groovy and vaguely familiar with Scala. had in mind JavaScript-like thing, this v.probably the same ting UR referring to. – Roam Nov 12 '13 at 04:40
  • This thread would be helpful http://stackoverflow.com/questions/781805/defining-a-class-while-a-java-application-is-running – Dzung BUI Nov 12 '13 at 04:41
  • 2
    Why exactly are you trying to avoid defining a class? What's the issue with that? – JimN Nov 12 '13 at 04:42
  • @JimN, I think the OP wants the succinctness of something like `{foo:'bar', baz:0}`, like Javascript. – Paul Draper Nov 12 '13 at 04:45
  • Ok. If you're fine with giving up type safety, you might prefer to use a scripting language instead. But in Java you could do: Arrays.asList(a, b); – JimN Nov 12 '13 at 04:52
  • Instead of creating a new class on the fly, you could save the values in a `Map`. – LaurentG Nov 12 '13 at 04:57

0 Answers0