Chris Cashwell
Chris Cashwell

Reputation: 22859

Dynamic Fields and/or Artificial Methods

I work with a dynamic Dataset model, which (in short) takes in attributes and stores them in a Map like this...

Dataset dataset = new Dataset();
dataset.setAttribute("name", "value");

...for later recovery, like this...

String value = dataset.getAttribute("name");

...and that has worked wonderfully for my purposes. But now I'm in a place where I'd like to use a templating engine to dynamically generate HTML. In the template, it's not ideal for me to do a lot of ${dataset.getAttribute("name")}. It would be rather nice if I could create artificial methods whenever something was added to a Dataset. For instance, if I did this...

dataset.setAttribute("name", "value");

...I'd like to be able to retrieve it like this...

String name;
name = dataset.name;
//or
name = dataset.getName();

...but so far I haven't been able to pull it off. What approach might I take here? Is it even doable?

Edit:

I understand that Velocity offers Property Lookup Rules to try to resolve dataset.name to dataset.get("name"), and that's great, but I need to know how to achieve this in the case that Velocity isn't the target as well.

Upvotes: 0

Views: 380

Answers (4)

RHSeeger
RHSeeger

Reputation: 16262

From what I've seen, it's fairly common for template engines for Java to support both

  • getters/setters of the form getAttribute, and
  • implementation of the Map interface

Before you spend too much time looking for a more generic solution (assuming the above won't be supported like it is in Velocity), it's probably worth taking a look at the other engines to see if any of them don't support it. If all your possible targets do, then you're probably fine relying on it.

I'm a big fan of making sure you actually have a problem before you spend the time to solve it.

Upvotes: 0

Stanislav Levental
Stanislav Levental

Reputation: 2225

You can use Dynamic Spring proxies with AOP technology or CGLib proxies. AOP could be used to describe getters like this : execution(public * com.bla.YourClass.get*())")

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691735

See http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html#propertylookuprules

If your method was named get(String attribute) rather than getAttribute(String attribute), you could use the same syntax as for regular properties. So, either refactor your class, or add an additional get method that does the same thing as getAttribute, or transform your object into a Map, which has a get method.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533520

In the past I have generated POJOs dynamically with Objectweb's ASM. This has the benefit that the underlying fields are type safe and much more efficient (esp for privative values)

Upvotes: 0

Related Questions