How to use bean without get and set in freemaker?



I have a class like this.

 public class User {
   public String username;
   public String age;
}

When i use freemarker.

${user.username!}

I didn’t get anything.

But if I change the class like this

   public class User {
        public String username;
        public String age;

        public String getUsername() {
           return username;
        }
   }

I can get value.

How to use bean without get and set in freemaker?

Because I have too many class without get and set.

I try lombok but it’s not what I want.

Answer

By default freemarker only exposes the JavaBean properties and public methods.

But you can configure the ObjectWrapper to expose all expose public, non-static fields:

Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
DefaultObjectWrapperBuilder wrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_27);
wrapperBuilder.setExposeFields(true);
cfg.setObjectWrapper(wrapperBuilder.build());
    


Source: stackoverflow