Skip to main content

Embedded Text via XML Annotations

Posted by evanx on April 16, 2007 at 5:08 AM PDT

We hear talk of introducing "native XML" into Java7. I'm not sure what form that might take?

Embedding HTML and SQL (and JavaScript et al) "text" into Java is cumbersome eg. using multi-line concatenated string literals. And this doesn't lend itself towards leveraging IDEs eg. for auto-completion, error-detection and syntax-highlighting. What might work for me is allowing "annotations" that are correctly formed multi-line XML text, as a mechanism to embed "structured" text into Java code in a way that is easy to type (and cut and paste) and easy to read (especially if the IDE does some syntax highlighting).

Then i could use these annotations for HTML snippets as follows.

public class HTMLBuilder {
   ...
   <html xmlns="html" id="sectionHeadingDiv">
      <div class="sectionHeadingStyle" />
   </html>
   public String getSectionHeadingHTML(String heading) {
      HTML snippet = getAnnotationHTML("sectionHeadingDiv");
      snippet.getChildElement("div").setText(heading);
      return snippet.toString();
   }
}

Also for SQL...

public class PersonDao {
   ...
   <sql xmlns="sql" id="selectPersonByPersonId">
      <query>
         select * from person
         where person_id = :personId
      </query>
   </sql>
   public Person getPerson(String personId) throws SQLException {
      SQL query = getAnnotationSQL("selectPersonByPersonId");
      query.setParameter("personId", personId);
      return (Person) query.fetch(Person.class);
   }
}

and also other any other cases where i might wanna embed multi-line text into a Java class, eg. maybe some dynamic scripting stuff.

The compiler might just treat these as String annotations, and an Ant task might verify the XML at compile time, and IDE's could hopefully join in the fun as well (with auto-completion, highlighting, verification). Waddaya think?