title: Freemarker: access public field with no getter in template
body: <p>I'm setting up views in a Dropwizard app and ran into a curious issue with Freemarker.</p>
  
  <p>Following the <a href="https://www.dropwizard.io/1.3.12/docs/manual/views.html" rel="nofollow noreferrer">docs here</a> I set up a very simple example as follows</p>
  
  <pre class="lang-java prettyprint-override"><code>public class ExampleFreemarkerView extends View {
    private Foo foo;
  
    public ContractHtmlView(Foo Foo) {
      super("FooView.ftl");
      this.foo = foo;
    }
  
    public Contract getFoo() { return foo };
  }
  
  public class Foo {
    public String bar = "Hello World";
  }
  </code></pre>
  
  <p>With <code>FooView.ftl</code></p>
  
  <pre><code>&lt;html&gt;
    &lt;body&gt;
      &lt;h1&gt;${foo.bar}&lt;/h1&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Expected output when rendering <code>ExampleFreemarkerView</code> is an HTML document displaying <code>Hello World</code>.</p>
  
  <p>What actually happens is Freemarker throws an exception, complaining that <code>${foo.bar}</code> - specifically <code>bar</code> - is undefined.</p>
  
  <p>This appears to be because <code>bar</code> is a public field, without a getter. When I add a <code>public String getBar() { return bar; }</code> getter to <code>Foo</code>, it works.</p>
  
  <p>I'm somewhat surprised that this is the case - i.e. that Freemarker seems to require getters and won't work with public fields out of the box. I'm deliberately using public fields instead of getters/setters on my model objects, so adding getters just to make Freemarker work isn't a solution I'll consider.</p>
  
  <p>I've googled around a lot and read through the Freemarker docs, and just can't find any way to 'turn on' this behaviour in Freemarker. <strong>Is it possible?</strong></p>
  
  <p>Just for interest - I also tried the above example, exactly the same, but with a Mustache template and public fields work fine there (i.e. <code>{{foo.bar}}</code> renders <code>Hello World</code> without issue). That solves the immediate problem, so this question is mostly just out of curiosity or in case I decide to use Freemarker over Mustache for other reasons.</p>
  
  <hr>
  
  <p><strong>Edit based on comments</strong> - <em>I understand that Freemarker does this (insists on getters out the box) to follow the Java Beans spec, but most libraries in the Java ecosystem support public fields - Hibernate and Jackson being prominent examples - to the extent I personally view it as an equally valid standard and find libraries not supporting it out the box surprising.</em></p>