1
votes

Using CodeModel, is there a way to control the order of modifiers? Specifically when creating fields.

CodeModel seems to have it's own definition of modifier order which differs than that of the Java Language Specification and products like SonarQube and CheckStyle:

https://sonar43.spring.io/rules/show/squid:ModifiersOrderCheck?layout=false http://checkstyle.sourceforge.net/config_modifier.html

Modifiers should appear in the following order:

  1. Annotations
  2. public
  3. protected
  4. private
  5. abstract
  6. static
  7. final
  8. transient
  9. volatile
  10. synchronized
  11. native
  12. strictfp

This sample code:

// Create field for serialVersionUID
JFieldVar field1 = newClass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID");
field1.init(JExpr.lit(1L));

Produces the following modifiers that does not follow suggested order:

private final static long serialVersionUID = 1L;
1

1 Answers

0
votes

This is not possible*. Not even nasty reflection hacks will do it. The order of the modifiers is determined by the JMods#generate(JFormatter) method (at the bottom). Unfortunately, the JMods class has only a single constructor that is explicitly declared as private.


*Of course, you can add another layer of instrumentation, bytecode assembly or similar, or just create a modified version of CodeModel for local use. But there is no non-intrusive way of changing the modifier order.