Creating Annotations is Fun! Too Much Fun?

Once again Lukas Eder has written an article I mostly agree with – but not completely. Lukas claims Annotations have become an antipattern.

The nice thing about annotations is you can define your own annotation. It’s easy, and it’s extraordinary popular among framework designers. So we see annotations in the bean validation API, in JPA, in CDI, in JSF, in EJBs, WebServices and Rest and much more.

Annotations – a programming language of their own

While I absolutely love these annotations, there’s a problem: they are starting to become a programming language of their own. What do you think about something like this?

@NotNull
@Size(min=6,max=10)
@Pattern("[a-zA-Z]+")
@Inject @UserID
@Column(name="userID")
private String userID;

@Valid
@ManagedProperty("#{customer.account}")
@OneToOne
private Account account;

Continue reading

Newsflash: Java to Scala Converter

JavaToScala.com may help you to learn Scala. It takes an arbitrary Java class and converts it to Scala.

Naturally, this approach emphasizes the similarities between the two languages. The few examples I tried were converted into solid Scala classes, but nothing out of the ordinary. The converter won’t introduce a case class or a trait if it seems fit. However, emphasizing the similarities is not a bad thing: many Java programmers are scared away from Scala after seeing advanced code.

The core of the converter is another project available on GitHub: Scalagen is a Maven plugin converting Java source code to Scala. The project home page states that the converter isn’t perfect, but may introduce errors for certain Java constructs, so I take it the same applies for JavaToScala.com. But still, it’s an interesting way to get familiar with Scala.

BootsFaces 0.6.6, Easter Edition

Fork me on GitHubStop looking for our Easter egg: you’ve found it. The BootsFaces team celebrate Easter with a new version of their responsive JSF framework. By now, BootsFaces is available on Maven Central, and in a couple of days it’ll arrive on the jCenter repository.

Basically, BootsFaces 0.6.6 is a bug fix release. There are also a number of minor improvements, such as adding the style attribute to a number of components that ignored in in the previous version.
Continue reading

What’s New in PrimeFaces 5.2?

The next version of PrimeFaces is planned to be released on April 6, 2015. Continuing what already has become a tradition, BeyondJava.net gives you a round-up of what’s new and noteworthy in in PrimeFaces 5.2.

The list isn’t complete, by the way. Among other things the PrimeFaces team have improved the screen reader support and closed more than 200 issues.
Continue reading

How to Embed a Servlet or an HTML Page in a JSF 2.x View

As trivial as the task may sound, hardly anybody seems to embed a servlet or an HTML page in a JSF view. That’s the impression my team and I got after a lengthy Google investigation. Finally we found OmniFaces, better known as the Swiss Army Knife of JSF.

OmniFaces is one of those JSF libraries that are different: It’s not about visual widgets (not in the first place, at least), but it’s full of other useful stuff. There’s the FullAjaxExceptionHandler BeyondJava.net reported about in an earlier article. There are several useful converters that make using comboboxes (or SelectOneMenus in JSF speak) much simpler. There’s the useful CombinedResourceHandler I’m going to cover soon. And there’s the component of the day: <o:resourceInclude />.
Continue reading

AngularFaces 2.1.4 published

Fork me on GitHubToday I’ve published AngularFaces 2.1.4 on MavenCentral. It should also arrive on JCenter within the next few days. The new version fixes a couple of annoying bugs, so I recommend to update soon.

New, improved documentation

There’s also news from the documentation page of AngularFaces. Currently, it’s moving from www.angularFaces.com to https://www.angularFaces.net. The new documentation page is an AngularFaces application featuring BootsFaces 0.6.5, PrimeFaces 5.1 and Omnifaces 2.1. Among other things, running on a web server makes it possible to show interactive live demos instead of static screenshots.

Continue reading

Scala.js

When I heard about Scala.js a couple of years ago, I thought to myself: “Well, that’s an interesting project, but sure it’s bound to fail”. Only it didn’t. The other day I’ve stumbled over an impressive technology demo. You can write a ray tracer in object-oriented and functional Scala, compile it to Javascript an run it in the browser. Ray tracers are power-hungry, so the good performance shows that Scala.js generates surprisingly good code. I didn’t run benchmarks, but judging from what I’ve seen I believe Scala.js is “good enough” on a modern browser. Native Javascript may be faster, but in many cases you won’t notice the difference.
Continue reading

Getting Started with BootsFaces: Responsive Design

BootsFaces is a JSF framework adding Bootstrap to JSF pages. One of the more attractive traits of Bootstrap is its built-in responsive design. Probably you already know the idea: screen elements are resized to fit on smaller screens. If everything else fails, Bootstrap starts to stack screen elements over each other if they can’t be displayed side-by-side. Usually, that doesn’t look as good as the original design aimed at larger screen estates, but the bottom line is that the application can be used even on small phones. Maybe you have to scroll a lot on a small device, but that’s a small price to pay. Without Bootstrap you’d have to scroll both horizontally and vertically, which is clearly worse.

Let’s write a simple BootsFaces application showing how easy it is to add responsive design to JSF applications. I’ve prepared a repository on GitHub, so you can check out the source codes used in this article. Today’s project is the subfolder ResponsiveDesign of this repository.
Continue reading

Newsflash: Google to Support AngularJS 1.x Longer, Dropping AtScript

According to Jaxenter, the AngularJS team reacted to the harsh reaction of the Javascript community on Google’s AngularJS 2.0 plans.

As a consequence, they decided to support AngularJS 1.x longer, giving companies who’ve already invested in AngularJS applications more time to migrate to AngularJS 2.0. Plus, they decided to drop AtScript. Instead, the team decided to merge AtScript with Microsoft’s TypeScript. That’s a pity because AtScript seemed to be an interesting language, but at the same time it’s good news since alternative browser languages start to cannibalize each other’s market share.

Read the full story at Jaxenter.

By the way, the original AngularJS 2.0 plans BeyondJava.net reported about have changed considerably in the meantime. The AngularJS team listened to the feedback of the community and adapted their former, much more radical ideas in order to align better with existing editors, existing tools and older browsers. Read the current state of the discussion at the AngularJS design documents folder.

BootsFaces 0.6.5 Published on Maven Central

After a while, our team is finally proud to publish the new v0.6.5 release.
This time we added more examples, a couple of handy components and exciting features. Here’s a short summary of the highlights:

  • Font Awesome Support ( #23 , #39 , #53 )
  • compatibility to both Oracle Mojarra and Apache MyFaces
  • improved AngularFaces Integration
  • Primefaces integration
  • Omnifaces integration
  • and better documentation.

Continue reading

Newsflash: Hope for Groovy

Pivotal’s recent announcement to drop both Groovy and Grails shook the Groovy community. The entire Java community, actually. Can we afford to invest in an open source project run by a company? Companies are sold and bought all the time, and the new owner may drop the previous owner’s pet projects without warning. That’s the story of Groovy and Grails.

I can’t help but wonder what that means to other projects. What if management decides to cut costs by releasing a project to freedom? You get the point: this move cost a lot of trust in frameworks run by a company. Any company, actually.

Among other things, the affair shows that open source isn’t a free lunch. Why don’t you support a project you’re fond of? It’s easy: tweet about it, or report a bug. You may even complain about the lousy documentation. That’s not a big deal, but it helps the developers a lot. They learn their documentation is read, and start to improve it.

At least in the case of Groovy, there’s hope. Guillaume Laforge, the public face of Groovy, has found a new job at a company that uses Groovy for their products. He won’t be able to work on Groovy full-time, but still, Guillaumes statement on reddit sounds encouraging:

Of course Groovy lives on! And I’ll still be wearing my Groovy hat on, even if only part time during my day job at Restlet. The project will indeed continue to be developed, with new features, performance improvements, more Java 8 related features, etc. We’re also going to announce in the coming days that the project is joining a foundation, to make the project more resilient!

That’s the second good news, provided it comes true. The Groovy project isn’t going to be homeless, but will be run by a foundation, which hopefully gives it an opportunity to flourish as lively as it did in the past.

Dig deeper

Guillaume Laforge joins Restlet
Let’s make APIs Grooyer
Discussion on reddit on the topic
InfoQ on the future of Groovy
Pivotal’s announcement to drop Groovy and Grails

Hibernate Cheat Sheet

Recently I wanted to write a small state-of-the-art Hibernate application. To my surprise, I didn’t find information about Hibernate 4 and the XML-free documentation easily. It’s all there, but it’s buried under tons of old-school tutorials and Spring tutorials. So here’s my small collection of what I’ve found out.

I’ll describe both the standard JPA and pure Hibernate approach. That’s because I didn’t find out how to configure JPA without XML yet.
Continue reading

AngularFaces 2.1 Blurs the Difference Between JSF and HTML

I always considered JSF to be to verbose, to ceremoniously. AngularFaces allows you to write JSF pages that almost look like HTML pages.

What it looks like

JSF 2.2 introduced the new HTML5 style of writing JSF pages. Basically, that’s ordinary HTML decorated by a few JSF attributes. AngularFaces picks up this idea and takes it to another level. For example, look at this snippet from my Tetris demo that demonstrates both BootsFaces and AngularFaces 2.1 at the same time:

  <body style="width:1000px" 
        ng-controller="AngularTetrisController" 
        ng-app="AngularTetris" 
        addLabels="false">
    <container>
      <form>
        <tabView>
          <tab title="Settings">
            <b:panelGrid colSpans="3,9">
              <selectBooleanCheckbox value="{{settingsBean.preview}}" 
                                     caption="preview (not implemented yet)" />
              <selectBooleanCheckbox value="{{settingsBean.ignoreGravity}}" 
                                     caption="gravity"/>
              <inputText value="{{settingsBean.numberOfColumns}}" 
                         label="columns (width)"/>
              <inputText value="{{settingsBean.numberOfRows}}" 
                         label="rows (height)"/>
            </b:panelGrid>
            <b:commandButton value="apply changes" ng-show="showApplyButton" />
            <messages showSummary="true" showDetail="true" globalOnly="true"  />
          </tab>
        </tabView>
      </form>
    </container>
  </body>

The embedded preview doesn’t work perfectly because of the scrollbar. Visit http://angularfaces.net/tetris for a better experience.


Continue reading

Final Version of AngularFaces 2.1 Published

Fork me on GitHubAngularFaces 2.1 is more than a bug fix release. It contains a couple of features I deliberately postponed in order to get a thoroughly tested version 2.0 out in times. The list below counts no less than 15 improvements. One of the improvements has nothing to the with code: I put AngularFaces 2.1 under an Apache V2 licence, which is much more liberal than the GPL licence of the previous version.

Examples and code snippets

Pictures say more than words, so let’s start with a couple of screenshots and code snippets. Click the tabs to see the source codes.

ng-table is a great client-side datatable component written in AngularJS. Thus, it’s a natural fit to AngularFaces.

<table ng-table="tableParams" class="table ng-table-responsive">
  <tr ng-repeat="car in $data">
    <td data-title="'Brand'" sortable="'brand'">{{car.brand}}</td>
    <td data-title="'Type'" sortable="'type'">{{car.type}}</td>
    <td data-title="'Year'" sortable="'year'">{{car.year}}</td>
    <td data-title="'Color'" sortable="'color'">{{car.color}}</td>
    <td data-title="'Mileage'" sortable="'mileage'">{{car.mileage}}</td>
    <td data-title="'Price'" sortable="'price'">{{car.price}}</td>
    <td data-title="'Fuel'" sortable="'fuel'">{{car.fuel}}</td>
    <td data-title="'Select'">
      <button class="carFilterButton" jsf:action="#{selectionBean.showDetails()}"
        ng-click="selectionBean.carAsJSon=afToJson(car);">show me!</button>
    </td>
  </tr>
</table>
<input jsf:value="{{selectionBean.carAsJSon}}" style="display:none" addLabel="false"/>
<prime:messages globalOnly="false" />
var app = angular.module('CarShop', ["angularfaces", 'ngTable', 'ngTableExport']).
controller('CarShopController', function($scope, $filter, ngTableParams) {
  // This initializes the Angular Model with the values of the JSF bean attributes
  initJSFScope($scope);
  $scope.activeSelections=0;
  
  $scope.select = function(car) {
    console.log(car);
    $scope.selectionBean.carAsJSon=car;
    return true;
  }
  
  $scope.showIfSet = function(ngmodel) {
    if (typeof(ngmodel)=='undefined') {
      return "hidden";
    }
    if (null==ngmodel || ngmodel=="") {
      return "hidden";
    }
    $scope.activeSelections++;
    return "";
  }
  
  $scope.filterBoxStyle=function(){
    var width=400+100*$scope.activeSelections;
    return "" + width + "px";
  }
  
    $scope.tableParams = new ngTableParams({
        page: 1,                  // show first page
        count: 10,                // count per page
        sorting: { brand: 'asc' } // initial sorting
    }, {
        total: $scope.carPool.selectedCars.length, // length of data
        getData: function($defer, params) {
          params.settings().counts=[5, 10, 'all']; // todo: that's a hack!
          var rows = $scope.carPool.selectedCars;
          if (params.filter()) rows=$filter('filter')(rows, params.filter());
          if (params.sorting()) rows = $filter('orderBy')(rows, params.orderBy());
          var page = params.page();
          var pageLength = params.count();
          if (pageLength=='all') 
          $defer.resolve(rows);
          else
            $defer.resolve(rows.slice((page - 1) * pageLength, page * pageLength));
        }
    });

})

Many business applications consist of long forms. AngularFaces simplifies writing such forms by adding labels and messages (including internationalization) automatically. If possible, it validates the form on the client, thus reducing the server load.

     <prime:panel header="If you want to buy this car..."
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:inputText value="#{carBean.brand}" />
          <prime:inputText value="#{carBean.type}" />
          <prime:inputText value="#{carBean.price}" />
          <prime:inputText value="#{carBean.mileage}" />
          <prime:inputText value="#{carBean.color}" />
          <prime:inputText value="#{carBean.year}" />
          <prime:inputText value="#{carBean.fuel}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:panel
        header="... we need some informations about where to deliver it:"
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:inputText value="{{customerBean.lastName}}" />
          <prime:inputText value="{{customerBean.firstName}}" />
          <prime:inputText value="{{customerBean.dateOfBirth}}" />
          <prime:inputText value="{{customerBean.emailAddress}}" />
          <prime:inputText
            value="{{customerBean.iAgreeToTheTermsAndConditions}}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:panel
        header="Please confirm you are a human by answering this simple question:"
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:outputLabel for="captchaField"
            value="{{customerBean.captchaQuestion}}" />
          <prime:inputText required="false" id="captchaField"
            value="{{customerBean.captcha}}"
            ng:captcha="{{customerBean.expectedCaptcha}}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:commandButton 
        action="#{customerBean.buy(carBean)}"
        value="Buy this car! (Non-AJAX)" ajax="false"
        styleClass="carFilterButton {{showDetailsClass()}}" ng-disabled="myForm.$invalid"
        style="{{myForm.$invalid?'color:#888':''}}" />
var app = angular.module('CarShop', ["angularfaces"]).
controller('CarShopController', function($scope, $filter) {
  // This initializes the Angular Model with the values of the JSF bean attributes
  initJSFScope($scope);
  $scope.doShowDetails = function() {
    if (typeof($scope.customerBean)=="undefined"||
      typeof($scope.customerBean.showDetails)=="undefined") {
      return false;
    }
    return $scope.customerBean.showDetails;
  }
  $scope.showDetailsClass = function() {
    if ($scope.doShowDetails()) 
      return "";
    else
      return "hidden";
  }
  $scope.showFinishedTransactionClass = function() {
    if ($scope.doShowDetails()) 
      return "hidden";
    else
      return "";
  }
  
  $scope.buttonEnabledStyle = function() {
    if ($scope.myForm.$invalid) 
      return "color:#888";
    else
      return "";
  }

});

app.directive('captcha', function() {
  return {
    require : 'ngModel',
    link : function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (typeof(viewValue)=="undefined" || viewValue==null) {
          ctrl.$setValidity('captcha', false);
          return viewValue;
        }
        if (viewValue!=attrs["captcha"]) {
          ctrl.$setValidity('captcha', false);
          return viewValue;
        } else {
          ctrl.$setValidity('captcha', true);
          return viewValue;
        }
      });
    }
  };
});

The JSF view below shows how to exchange arbitrary data between client and server using the new <ngsync /> tag.

The form contains seven input fields, so the XHTML code repeats itself. I omitted most of the repetitions. The XHTML code uses the new HTML5 style of JSF 2.2:

    <ngsync value="{{staticOptionBean.brands}}"   direction="serverToClient" once="true" />
    <ngsync value="{{staticOptionBean.colors}}"   direction="serverToClient" once="true" />
    <ngsync value="{{dynamicOptionBean.types}}"   direction="serverToClient" cacheable="true" />
...
    
    <!-- ngsync doesn't transport the entire bean recursively, so we have to list each attributes we want to send -->
    <!-- will be fixed in a future AngularFaces version -->
    <ngsync value="{{filterBean.type}}"     direction="serverToClient" cacheable="true" />
    <ngsync value="{{filterBean.brand}}"    direction="serverToClient" cacheable="true"/>
    <ngsync value="{{filterBean.counter}}"  direction="serverToClient" cacheable="true" />
    <!-- end of ngsync workaround -->
    
    <ngsync value="{{filterBean}}" direction="clientToServer" id="filterSyncID" />
    <ngsync value="{{settingsBean}}" direction="clientToServer" id="settingsID" />
    
    <div class="carFilterBox"> 
      <div style="font-weight:bold;font-size:125%">What kind of car are you looking for?
      </div> 
      <div>
        <table style="border-spacing:10px">
          <tr>
            <td width="150px">Brand</td>
            <td width="110px">Type</td>
            <td width="100px">Price</td>
          </tr>
          <tr>
            <td>
              <select id="filterbrand" ng-model="filterBean.brand" ng-options="brand for brand in staticOptionBean.brands track by brand"
                                    ng-change="filterBean.type=''">
                     <option value="">-- choose brand --</option>
              </select>
            </td>
            ...
          </tr>
          ...
           <tr>
            <td>
              <select ng-model="filterBean.yearText" ng-options="year for year in staticOptionBean.years track by year">
                     <option value="">-- choose year --</option>
                 </select>
            </td>
            <td>
              <button ng-show="activateAJAXButton()" class="carFilterButton" jsf:action="index.jsf">update counter
                <f:ajax render="angular" execute="filterSyncID settingsID"></f:ajax>
              </button>
            </td>
            <td >
              <button id="listCarsID" class="carFilterButton" jsf:outcome="table.jsf" >{{filterBean.counter}} cars</button>
            </td>
          </tr>
        </table>
      </div>
    </div>
var app = angular.module('CarShop', [ "angularfaces" ]).controller(
    'CarShopController', function($scope) {
      // This initializes the Angular Model with the values of the JSF
      // bean attributes
      initJSFScope($scope);
      
      $scope.activateAJAXButton = function() {
        if ($scope.settingsBean.updateImmediately)
          return false;
        else
          return true;
      };
      
      $scope.sendFilterToServer = function(newValue, oldValue) {
        if ($scope.settingsBean.updateImmediately) {
          if (newValue != oldValue) {
            try {
              $scope.afSendNGSyncToServer();
            } catch (e) {
              console.log("Ein Fehler ist aufgetreten: " + e);
            }
          }
        }
      };

      $scope.$watch('filterBean.brand', $scope.sendFilterToServer);
      $scope.$watch('filterBean.type', $scope.sendFilterToServer);
      $scope.$watch('filterBean.price', $scope.sendFilterToServer);
      $scope.$watch('filterBean.mileage', $scope.sendFilterToServer);
      $scope.$watch('filterBean.fuel', $scope.sendFilterToServer);
      $scope.$watch('filterBean.color', $scope.sendFilterToServer);
      $scope.$watch('filterBean.yearText', $scope.sendFilterToServer);
    })

Continue reading

AngularFaces 2.1: Apache License V2, AngularJS 1.3 and much more

Yesterday, I’ve published what I hope to be the last release candidate of AngularFaces on Maven Central. Basically, AngularFaces 2.1 RC5 already is the final version. I only called it a release candidate I did a few last-minute changes. I felt the need to run more tests.

AngularFaces 2.1 offers many new features. Today, I’ll present four of them: the new license, AngularJS 1.3, first-class divs and the new AJAX support contributed by Marco Rinck.
Continue reading

A Child’s Garden of Cache Effects

One of these days Joshua Bloch twittered a link pointing to “a child’s garden of cache effects”. Igor Ostrovsky demonstrates the effect of CPU caches using a high-level programming language, such as C#. Highly recommended!

When I read his article, I wondered if we can demonstrate the same effects in Java. At first glance, the odds are against us: Java isn’t compiled to native machine code, but to an intermediate byte code, which in turn may or may not be compiled to native machine code (depending on the circumstances). So, can we show cache effects in a Java program?

Yes, we can!
Continue reading

A Java Programmer’s Guide to Assembler Language

Imagine a programming language without variables. A language without function parameters and return values. A language without floating point numbers, maybe even without multiplication and division. A language without type casting. Without types, actually. Not to mention classes or objects. Join me in a journey to the world of assembler languages.
Continue reading

BootsFaces 0.6.0 Now Available on Maven Central

Maven coordinates

BootsFaces – the JSF framework that makes Bootstrap much more accessible to JSF programmers – is now available on Maven Central. To use it, add a dependency to your Maven pom.xml file:

<dependency>
    <groupId>net.bootsfaces</groupId>
    <artifactId>bootsfaces</artifactId>
    <version>0.6.0</version>
</dependency>

Gradle users activate BootsFaces by adding this line to their .gradle build file:

compile 'net.bootsfaces:bootsfaces:0.6.0'

Minified version and debug-friendly version

The version I’ve uploaded to Maven Central is a developer-friendly version containing minified Javascript and CSS code, but non-minified Java class files. In other words: you can debug it, and you can easily identify the offending line if you find an error in your production log.

There’s also a version of BootsFaces that has been minified more aggressively. Currently, the smaller and slightly faster version hasn’t made it to Maven Central yet. You can download it at our project showcase and the project GitHub repository.

License

BootsFaces 0.6.0 is available both under a GPL 3 and a LGPL 3 license.

But I’m already using another JSF framework!

BootsFaces coexists peacefully with PrimeFaces, AngularFaces and probably most other JSF frameworks. For example, you can use the layout components of BootsFaces (<b:row>, <b:column>, <b:panelGrid>, <b:panel>, <b:tabView> / <b:tab> and <b:navBar>) together with the powerful input and datatable widgets of PrimeFaces.

Of course you can also use BootsFaces as a full-blown JSF component framework, providing responsive design and native Bootstrap GUIs. It’s up to you.

Kudos

BootsFaces is an open source framework initiated and led by Riccardo Massera. Thanks to Riccardo, Emanuele Nocentelli and everybody else who contributed! This includes everybody who gave us feedback by reporting errors or feature requests by opening an issue on the GitHub repository. Your feedback matters!

Wrapping it up

Visit our project showcase and enjoy!

Programming Over Convention Over Configuration?

The Java community moved to a new paradigm during the last five years, and nobody talked much about it.

Act 1: Programming

When I entered the enterprise Java world, every programmer did what was expected from them. They wrote programs.

Act 2: Configuration over Programming

Enter Spring. Or EJB before version 3.0, for that matter. Programming – they said – is bad. It’s OK to write small modules, building blocks of your application that can be glued together. But the glue code needn’t be code. It’s better to adopt a declarative programming style. Design configurable modules, and configure them in XML. That programming model has great advantages: you can replace modules by different module as seems fit. Configuration gives you a big boost of productivity.
Continue reading

A Quick Guide to Writing Bytecode With ASM

My previous article gave you a short introduction on reading Java bytecode. Now let’s do it the other way round: today we’re going to write bytecode ourselves.

So grab your hex editor and get prepared to type endless sequences of cryptic numbers!

Wait – that’s not how we’re going to do it. Actually, I’m mostly interested in showing you the general idea. We’re going to cut a couple of corners. We’ll add code to an existing method of a class on your hard disk. And we’ll use a framework that does the hard work for us. You don’t have to download a hex editor. The Java class file format is a bit convoluted, so editing a Java class in a hex editor isn’t too much fun.

Observe the difference between a high-level language like Java and a low-level language like Java bytecode or assembler. Bytecode programmers have to think a lot smaller. A single line of Java code can translate to half a dozen bytecode instructions. Remember the for loop of the previous article: Depending on what you count, it consists of five to eight instructions. Programming in assembler is even worse: a single high-level instruction can trigger thousands of machine-code instructions, especially on older CPUs. Which in turn also means that high-level languages tend to be slow. They do a lot of things that could be streamlined in assembler. But nowadays hardly anybody wants to pay the price: your program may run faster, but you don’t program it quickly. The effort only pays in special areas such as games and hardware drivers.

Apart from showing you the different state of mind you need to adopt to program in a low-level language, the article also shows you how to get started with the ASM library. I picked a very small task: modifying a method of a class at runtime.
Continue reading