Gary
Gary

Reputation: 13912

JSON-like Object Syntax In Java

I hate to ask something so trivial, but I can't work this one out. I'm trying to create a basic object for convenience, like this:

triangle = {
  side: { A: 0, B: 0, C: 0 },
  angle: { a, b, c },

  function calcAngle(){}
}

Ideally, I'd like to just create a generic object on the fly. I'm only creating one "triangle", must I create a whole class for one instance? I'm sure this is answered somewhere, but I can't seem to word the question right for anything useful. For your amusement I'll post some of my failures:

public class TGUI{

// Attempt One
   public Object triangle = new Object(){ int test; };
   public static void main(String[] args) {
     triangle.test = 1;
     // ^- Cannot make a static reference to the non-static field triangle

     triangle tri = new triangle();
     // ^- Made the compiler cry; triangle cannot be resolved to as type
   }

// Attempt Two
   public class triangle{ int test; }
   public static void main(String[] args) {
       triangle tri = new triangle();
       /* ^- No enclosing instance of TGUI is accessible.  Must qualify the allocation with an enclosing instance of type TGUI (eg x.new A() where x is an instance of TGUI) */
   }

// Attempt Three
   public void triangle(){ int test = 1; }
   public static void main(String[] args) {
     triangle tri = new triantle();
     // ^- triangle cannot be resolved to a type
   }

// Attempt Four
   public TGUI(){ int test; }
   /* I'm gonna quit here, you get the idea */
}

Upvotes: 1

Views: 2555

Answers (4)

Hot Licks
Hot Licks

Reputation: 47739

public class Triangle {
    double sideA;
    double sideB;
    double sideC;
    double[] angles = new double[3];
    double calcAngle() {
        something;
        return somethingElse;
    }
}

Upvotes: 1

injecteer
injecteer

Reputation: 20709

indeed, you should use a JVM-based script language like Groovy to implement such dynamic things out of the box. You would create an instance of MetaClass and add all your fields on the fly. Another option for good ol' Java only would be to create a simple (marker?) interface and implement it as an anonymous inner class just where you need it.

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

Attempt 2 was closer. You needed a nested static class:

public static class triangle{ int test; }

(or triangle can be in a separate file).

It's still far from how Java operates on its static type system.

Upvotes: 1

djechlin
djechlin

Reputation: 60798

Ideally, I'd like to just create a generic object on the fly.

Then you shouldn't use a statically typed language.

The only ways to do this in Java are

  • use reflection (not what you want), or
  • use a JSON library,
  • give up typing entirely and use a Map<String, Integer>.

In your case, sounds like you just need an actual Triangle class though. Java requires lots of typing, better to get used to it than write bad code to avoid it.

Upvotes: 2

Related Questions