3

Right I am passing a Java object to the view:

Instead of listing all the fields as follows, I wonder whether it is possible to get all fields of the objects as collection (something like reflection in Java) and then to print them in a loop?

@(item: Item)

<li data-item-id="@item.id">
    <h4>@item.name</h4>
    <h3>@item.field1</h3>
    <h3>@item.field2</h3>
    ...
</li>

The second question is what HTML tags are most relevant (instead of li, h4, h3) to represent an object?

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
  • http://stackoverflow.com/questions/7457972/getting-public-fields-and-their-respective-values-of-an-instance-in-scala-java ? – Leo Sep 29 '13 at 20:28

1 Answers1

6

The solution to this is not using "something like" reflections but to actually use reflections. Any library or framework for this will be most likely based on reflections anyway.

The objects class provides all methods you need to get declared or both declared and inherited fields. The field class contains all information about the actual field, like its name, type or value.

Example

Some class to display on the page:

public class Item {
    public String foo = "bar";
    public int x = 23;
}

Template:

@(item: Item)
<ul>
  @for(field <- item.getClass().getDeclaredFields()) {
    <li>@field.getName() = @field.get(item)</li>
  } 
</ul>

Output:

<ul>
  <li>foo = bar</li>
  <li>x = 23</li>
</ul>

Keep in mind that the template might not be the right place to do this, especially if you maybe want to filter the fields or something. You should move the code to the controller, or even better to the model. Since you know the object is an Item, you could create a getFields() method in Item where you implement more complex logic and return a list of fields or field names.


The choice of semantic html tags really depends on the content of your fields. Generally speaking, if you only print the field name, a list of fields sounds reasonable. If you print names and values, you could use a definition list dl or maybe a table.

kapex
  • 28,903
  • 6
  • 107
  • 121