TIOBE Is (Unintentionally) Misleading; in Truth, Interest in Java Is Surging

Every now and then I see an article that cites the recently close "race" for "most popular programming language" between Java and C, according to the TIOBE Index -- almost inevitably followed by remarks about Java's long and painful decline. TIOBE uses a somewhat complicated formula for computing its ranking; but the core component of the method seems to be search statistics for the name of each language followed by the word "programming," for example, "Java programming." This makes a lot of sense, because if you go to Google Trends and search for, say, "Java" or even "JVM," you can readily see that those statistics include many searches that have nothing to do with the programming language Java or the Java Virtual Machine. Below is the current TIOBE graph of the 10 most popular languages over the past 13 years or so: The black line at the top is Java's TIOBE rating, while the nearby light blue line is C. One thing that stands out is that Java's "popularity" has been on a long, slow, decline, according to TIOBE's rating system. But does this mean that usage of Java is actually declining? I think not, for several reasons. First, Java is a mature language. Wouldn't it be reasonable for a mature language to receive fewer searches on search engines like Google, Yahoo, etc., since a broad swath of developers are already very familiar with the language? Meanwhile, today's hot new, programming fad might receive lots of searches, because it's "all the buzz" today? This seems possible to me, anyway. But there's another, more mathematical approach we can apply here. Let's use a snippet of TIOBE's own approach, and combine it with some other data, and see what the numbers say. Below is the Google Trends plot of "interest over time" in Java programming: According to this plot, "interest in Java" was at a peak perhaps in 2004 (but we don't see the data from before then), and today the level of interest is about 28% as high as it was then. But, what does this really mean? Google Trends rates search topics on the basis of the proportion of searches for that term amid all searches. So, what this plot is actually telling us is that the proportion of Google searches for "Java programming" today is about 1/3 of what it was in 2004. Again, the reason I stated above might be part of this. It's important too, though, that "interest" in the term "Java programming" has held quite constant since 2009. And here's where things get even more "interesting"... The table below shows the annual total number of Google searches, according to the site Statistic Brain: Year Total GoogleSearches (billions) 2013 2,162 2012 1,874 2011 1,722 2010 1,325 2009 954 2008 637 2007 438 Now, the Google Trends plot really tells us the level of "interest in Java programming" relative to the level of "interest" in all topics. Relative to all searches on Google, "Java programming" occupies a smaller proportion than was the case in 2004. But, if we use the table above to convert this "proportional interest" data into a scale that represents the total number of actual searches for "Java programming," we get something like this: Year Total GoogleSearches (billions) Relative Interest in'Java programming' Total Interest in'Java programming' 2013 2,162 28 138 2012 1,874 30 128 2011 1,722 30 118 2010 1,325 29 88 2009 954 29 63 2008 637 29 42 2007 438 34 34 Here, what I've done is use 2007 as a basis, and computed the "Total Interest" result by taking into account the growth of total Google searches in subsequent years. This shows us that, on a nominal basis, searches for "Java programming" on Google more than quadrupled between 2007 and 2013! Rather than Java being a language that's enduring a long, slow decline (as you might think from pulling up the TIOBE most popular languages plot), worldwide interest in Java is actually surging! Now, can we finally lay that "Java is dead" trope to rest??? Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham) AttachmentSize Tiobe201404.png105.92 KB JavaProgrammingGoogle.png23.9 KB

Posted by on 23 April 2014 | 4:20 pm

Using BDD with web-services: a tutorial using JBehave and Thucydides

Behavior Driven Development (BDD) is an approach that uses conversions around concrete examples to discover, describe and formalize the behavior of a system. BDD tools such as JBehave and Cucumber are often used for writing web-based automated acceptance testing. But BDD is also an excellent approach to adopt if you need to design a web service. In this article, we will see how you can use JBehave and Thucydides to express and to automate clear, meaningful acceptance criteria for a RESTful web service. (The general approach would also work for a web service using SOAP.) We will also see how the reports (or "living documentation", in BDD terms) generated by these automated acceptance criteria also do a great job to document the web service. Thucydides is an open source BDD reporting and acceptance testing library that is used in conjunction with other testing tools, either BDD testing frameworks such as JBehave,

Posted by on 22 April 2014 | 3:42 am

Discovering Java's runtime type information

Runtime type information (RTTI) refers to the correct identification of the type of your objects at run time. When you write code, it is generally desirable to do so in a way that takes advantage of OOP features like encapsulation and inheritance to make your program easily extensible, by for instance, as much as possible manipulating references to base classes and letting polymorphism work for you. Essentially, when you create a new object with a base class reference, the process necessarily involves an upcast to the base class from a more specialised type. There are many advantages to this style of programming not least of which includes the ability to simulate a more dynamic behaviour. Upcasting is a fairly straightforward process that the Java interpreter undertakes automatically, because there is very little risk associated with it. RTTI describes the reverse of this process when you wish to focus on a specific type for example to perform a particular operation. For instance, consider the following Game class hierarchy:- package runtime.types.java; abstract class Game {     public int players;     public String toString() {         return "Game";     }     void play() {         System.out.println("playing " + this + "()");     }}class Charade extends Game {     public String toString() {         return "CharadeGame";     }}class Chess extends Game {     public String toString() {         return "Chess";     }}class CardGame extends Game {     public String toString() {         return "CardGame";     }}class BlackJack extends CardGame {     public void shuffle() {         System.out.println("Shuffle cards");     }     public String toString() {         return "BlackJack";     }}class OnlineGame extends Game {     public String toString() {         return "OnlineGame";     }} This is a fairly accurate representation of the structure of libraries that exist within an OO paradigm, even though in reality some classes inherit from base classes in other packages. In the following code a List is configured to hold subtypes of the abstract Game class. Each type of Game is upcast to the List container which treats all elements as Game references having no memory of individual types. We can identify the benefit of RTTI in the playGame() method where we iterate through the list and the correct type is identified in the call to play() because polymorphism allows us to make the correct binding at runtime:- package runtime.types.java; import java.util.Arrays;import java.util.List; public class Arcade {     static void playGame(List<Game> options) {         for(Game selection : options)         selection.play();     }     public static void main(String[] args) {         List<Game> games = Arrays.asList(new Chess(), new CardGame(), new BlackJack());         playGame(games);     }}/* Outputplaying Chess()playing CardGame()playing BlackJack()*// The above example is the most basic form of RTTI and why polymorphism is understood to be a general goal in object oriented programming. There are other circumstances when you might need to identify a specific type, perhaps to enable some operation unique to a specific type, circumstances for which you can not rely on polymorphism by itself. Java allows you to discover runtime type information in one of two ways. The first approach assumes all type information is available at compile time which you can obtain by querying the object reference. For instance, suppose we wanted to ensure the cards are shuffled before playing a game of BlackJack. We could use RTTI to identify this specific type in order to call the appropriate method:- package runtime.types.java; import java.util.Arrays;import java.util.List; public class GettingType {     public static void playGame(List<Game> options) {         for(Game selection : options) {             Class<? extends Game> type = selection.getClass();             if(type.isAssignableFrom(BlackJack.class))                 ((BlackJack)selection).shuffle();             selection.play();         }     }     public static void main(String[] args) {         List<Game> games = Arrays.asList(new Chess(), new BlackJack(), new Charade());         playGame(games);     }}/* Outputplaying Chess()Shuffle cardsplaying BlackJack()playing Charade()*// In this instance, we query the object reference for type information using the getClass() method, and then apply the isAssignableFrom() method to the resulting reference determine if this class is the same or a superclass of the BlackJack class. If it is, we cast the object to a BlackJack object and then call shuffle(). The logic of type as you will no doubt come to understand is sound and quite uncomplicated. You can also use the instanceof keyword to check for the type of an object, for example prior to making a cast:- package runtime.types.java; public class TypeTest {     public static void main(String[] args) {         Game aGame = new BlackJack();         if(!(aGame instanceof BlackJack))             System.out.println("Not an instance");         ((BlackJack)aGame).play();     }}/* Outputplaying BlackJack()*// The other approach to discovering type information is to make use of a reflection mechanism by which means you can discover and use previously unavailable class information, exclusively at runtime. In any event, either approach requires a sound knowledge of how Java represents type information at runtime. The Class object Java uses instances of the class Class to represent type information at runtime. Type refers to the classes and interfaces in a running Java application which are automatically loaded by the Java Virtual Machine (JVM) using a special ClassLoader mechanism. In effect, there exists a Class object for every class that is a part of your program which consists of information about your class and is used for creating all the other objects of your class. You can get a reference to this Class object by calling the getClass() method as we did in a previous example. However in circumstances where this option might not be available, you can create a Class reference directly which can then be manipulated just like you do any other reference to conveniently discover all sorts of type information. You can return a Class reference by either calling the static forName() method or by using the class literal. Here is an example using both techniques;- public class GettingTypeInfo {     static void printTypeInfo(Class<? extends Game> whichClass) {         System.out.println("Class name - " + whichClass.getName());         System.out.println("Simple name - " + whichClass.getSimpleName());         System.out.println("isInterface - " + whichClass.isInterface());         System.out.println("Package - " + whichClass.getPackage());         System.out.println("SuperClass " + whichClass.getSuperclass());     }     public static void main(String[] args) throws ClassNotFoundException,                                  IllegalAccessException, InstantiationException {         Class<? extends Game> aClass = Class.forName("runtime.types.java.BlackJack");         //class literal syntax         Class anotherClass = Chess.class;         printTypeInfo(aClass);         System.out.println("isInstance - " + aClass.isInstance(new BlackJack()));         System.out.println("------------------------------- ");         printTypeInfo(anotherClass);         System.out.println("isInstance - " + anotherClass.isInstance(new Game()));         System.out.println("------------------------------- ");         Object anObj = aClass.newInstance();         System.out.println("NewInstance " + anObj.toString());      }}/* OutputClass name - runtime.types.java.BlackJackSimple name - BlackJackisInterface - falsePackage - package runtime.types.javaSuperClass class runtime.types.java.CardGameisInstance - true-------------------------------Class name - runtime.types.java.ChessSimple name - ChessisInterface - falsePackage - package runtime.types.javaSuperClass class runtime.types.java.GameisInstance - false-------------------------------NewInstance BlackJack*// The first statement in the main() makes use of the static forName() method to obtain a valid reference to the BlackJack Class, by contrast, the second statement makes use of a class literal to achieve the same effect. Both techniques are equally valid, but have subtle implications related to the way the class object is initialised. Notice the use of generic syntax with Class types in particular in the call to the forName() method. Generics provide a way to constrain objects to subtypes of a particular type. Here the wildcard symbol symbol is used in combination with the extends keyword to constrain all references to subtypes of Game. Class references also work fine without the use of generics, however it is advisable to use generic syntax as you are likely to find out about mistakes much sooner The printTypeInfo() method displays output from a number of methods available to objects of the class Class providing access to useful type information. The isInstance() and newInstance() methods are also used in the main() to test for compatibility and create a new instance respectively. As you become used to working with types, you will find them useful in circumstances where you might wish to be able to identify individual types perhaps for some specific purpose. For instance, suppose you wanted a way to keep a track of the number of individual Game types generated by your application. The first thing you might need is a way to link the initialisation of each Game object with it's corresponding Class object. One way to do this might be to use a variation of the template design pattern to create an abstract method that returns a list of types with which you might generate new instances of Game types:- package runtime.types.java; import java.util.List;import java.util.Random; public abstract class InitGame {     static private Random generator = new Random();     public abstract List<Class<? extends Game>> getTypes();      public Game aRandomGame() {         int index = generator.nextInt(getTypes().size());         try {             return getTypes().get(index).newInstance();         } catch(InstantiationException ref) {             throw new RuntimeException(ref);         } catch(IllegalAccessException ref) {             throw new RuntimeException(ref);         }     }     public Game[] createGames(int capacity) {         Game[] arrayOfGames = new Game[capacity];         for(int i = 0; i < capacity; i++)             arrayOfGames[i] = aRandomGame();         return arrayOfGames;     }} Essentially, this class uses a random number generator to index into a list of types in order to instantiate a new Game object. A second method uses this pseudo-random algorithm to return an array of games. As with all abstract classes, an inheriting class will need to implement the abstract getTypes() method. The following class uses class literals to create a list of Class references:- package runtime.types.java; import java.util.Arrays;import java.util.List; public class GameTypeCreator extends InitGame {     @SuppressWarnings("unchecked")     public static final List<Class<? extends Game>> gameTypes = Arrays.asList(Chess.class,                                               CardGame.class, BlackJack.class,                                                   Charade.class, OnlineGame.class);     public List<Class<? extends Game>> getTypes() {         return gameTypes;     }} The final class in this sequence uses a Map to track the number individual type of Game objects created. Here's how:- package runtime.types.java; import java.util.HashMap;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map; class Util {     static public Map<Class<? extends Game>, Integer> mapData(List<Class<? extends Game>> key, int value) {            Map<Class<? extends Game>, Integer> data = new HashMap<>();            Iterator<Class<? extends Game>> sequence = key.iterator();            while(sequence.hasNext())                   data.put(sequence.next(), value);            return data;     }}public class CountGame extends LinkedHashMap<Class<? extends Game>, Integer> {         public CountGame() {             super(Util.mapData(GameTypeCreator.gameTypes, 0));         }         public void count(Game aGame) {             for(Map.Entry<Class<? extends Game>, Integer> anEntry : entrySet())                 //Class.isInstance to dynamically test for types                 if(anEntry.getKey().isInstance(aGame))                     put(anEntry.getKey(), anEntry.getValue() + 1);         }         public String toString() {             StringBuilder aString = new StringBuilder("{");             for(Map.Entry<Class<? extends Game>, Integer> anEntry : entrySet()) {                 aString.append(anEntry.getKey().getSimpleName());                 aString.append("=");                 aString.append(anEntry.getValue());                 aString.append(", ");             }             aString.delete(aString.length()-2, aString.length());             aString.append("} ");             return aString.toString();         }     }     public static void main(String[] args) {         CountGame aGameCounter = new CountGame();         GameTypeCreator aGameTypeCreator = new GameTypeCreator();         for(Game aGame : aGameTypeCreator.createGames(15)) {             System.out.print(aGame.getClass().getSimpleName() + " ");             aGameCounter.count(aGame);         }         System.out.println();         System.out.println(aGameCounter);     }}/* OutputOnlineGame BlackJack Charade BlackJack BlackJack Chess CardGame Chess OnlineGame BlackJack BlackJack Chess BlackJack Charade Charade{Chess=3, Charade=3, BlackJack=6, OnlineGame=2, CardGame=7}*// In this example, a Map is preloaded using a mapData() utility that accepts a list of Class types restricted to subtypes of the Game class and an integer value, zero in this particular instance. In the count(), the isInstance() method is used to test for type and then increment the value entry by one. A Map can not contain duplicate keys and each key can only map to one value so it is the perfect tool for this kind of application. The toString() method is overridden to provide a formatted view of the Map. Adding a new type of Game is a simply a matter of making an update to the static gameTypes list in the GameTypeCreator class. This is a useful tool limited only by the fact that it can only be used to count types of Game because the Map has been preloaded with Game types. A more useful tool would be one that we could use to count any type:- package runtime.types.java; import java.util.HashMap;import java.util.Map; public class CountAnyType extends HashMap<Class<?>, Integer> {     private Class<?> baseType;     public CountAnyType(Class<?> aType) {         this.baseType = aType;     }     public void checkType(Object arg) {         Class<?> aType = arg.getClass();         if(!baseType.isAssignableFrom(aType))             throw new RuntimeException("Wrong type! " + arg);         count(aType);     }     public void count(Class<?> aType) {         Integer sum = get(aType);         put(aType, sum == null ? 1 : sum + 1);         Class<?> superClass = aType.getSuperclass();         if(superClass != null && baseType.isAssignableFrom(superClass))             count(superClass);     }     public String toString() {         StringBuilder aString = new StringBuilder("{");         for(Map.Entry<Class<?>, Integer> anEntry : entrySet()) {             aString.append(anEntry.getKey().getSimpleName());             aString.append("=");             aString.append(anEntry.getValue());             aString.append(", ");         }         aString.delete(aString.length()-2, aString.length());         aString.append("} ");         return aString.toString();     }     public static void main(String[] args) {         CountAnyType aTypeCounter = new CountAnyType(Game.class);         GameTypeCreator aGameCreator = new GameTypeCreator();         for(Game aGame : aGameCreator.createGames(15)) {             System.out.print(aGame.getClass().getSimpleName() + " ");             aTypeCounter.checkType(aGame);         }         System.out.println();         System.out.println(aTypeCounter);     }}/* OutputCharade Charade Chess BlackJack BlackJack BlackJack CardGame BlackJack Charade CardGame OnlineGame Charade Charade Chess CardGame{Game=15, Charade=5, BlackJack=4, OnlineGame=1, Chess=2, CardGame=7}*// We have introduced a checkType() method that allows us to verify that we are counting the correct type using the isAssignableFrom() method. The count() method in this example, first counts the specific type and then recursively counts the base type. You would be correct to imagine that it would be possible to make a more sophisticated design in our approach to generating Game objects in circumstances where we were unconcerned about keeping track of types or for that matter if we had to generate Game objects with a much greater frequency. Here is an approach that makes use of the Factory design pattern by registering factories for the types to be created directly in the base class:- package runtime.types.java; import java.util.ArrayList;import java.util.List;import java.util.Random; interface GameFactory<T> { T createGame(); } class Game {     static List<GameFactory<? extends Game>> factory = new ArrayList<>();     private static Random generator = new Random();     public String toString() {         return getClass().getSimpleName();     }     static {         factory.add(new Charade.Factory());         factory.add(new Chess.Factory());         factory.add(new Scrabble.Factory());         factory.add(new Monopoly.Factory());         factory.add(new BlackJack.Factory());         factory.add(new OnlineGame.Factory());         factory.add(new VideoGame.Factory());     }     public static Game autoCreate() {         int index = generator.nextInt(factory.size());         return factory.get(index).createGame();     } }class PartyGame extends Game {}class Charade extends PartyGame {     public static class Factory implements GameFactory<Charade> {         public Charade createGame() { return new Charade(); }     }}class BoardGame extends Game {}class Chess extends BoardGame {     public static class Factory implements GameFactory<Chess> {         public Chess createGame() { return new Chess(); }     }}class Scrabble extends BoardGame {     public static class Factory implements GameFactory<Scrabble> {         public Scrabble createGame() { return new Scrabble(); }     }}class Monopoly extends BoardGame {     public static class Factory implements GameFactory<Monopoly>  {         public Monopoly createGame() { return new Monopoly(); }     }}class CardGame extends Game {}class BlackJack extends CardGame {     public static class Factory implements GameFactory<BlackJack> {         public BlackJack createGame() { return new BlackJack(); }     }}class OnlineGame extends Game {     public static class Factory implements GameFactory<OnlineGame> {         public OnlineGame createGame() { return new OnlineGame(); }     }}class VideoGame extends Game {     public static class Factory implements GameFactory<VideoGame> {         public VideoGame createGame() { return new VideoGame(); }     }}public class GameFactories {     public static void main(String[] args) {         for(int i = 0; i < 10; i++)             System.out.println(Game.autoCreate());     }}/* OutputCharadeOnlineGameCharadeBlackJackOnlineGameScrabbleScrabbleChessOnlineGameChess*// The GameFactory interface uses generic syntax and consequently is able to return a different type based on it's implementation. In this way, adding a new type of Game does not require too much effort, except to register it's inner GameFactory class in the factory list in the base class . The genius of this design is in its simplicity and this is exactly what design patterns are able to do. They provide you with the ability to encapsulate change. The Reflection Mechanism The RTTI mechanisms discussed thus far have in common the advantage of being able to discover type information for objects whose types will have been available at compile time, in other words these classes must have been compiled as a part of your program. Java uses reflection to discover and use classes at runtime about which you had no prior information. This capability is useful in circumstances where your application might need to make use of a foreign utility which might be accessed over a network connection, on the internet or in some other similar fashion to create and execute objects on remote platforms in a technique known as Remote Method Invocation (RMI). Java's reflection implementation consists of a number of classes within the java.lang.reflect library that can be used to represent the fields, methods and constructors after which they have been appropriately named. The Constructor class for instance provides access to a single class constructor, the Field class includes getter() and setter() methods to read and modify Field objects and the Method class includes an invoke() method by which means you might invoke the underlying method associated with the Method object. These classes implement the Member interface which reflects identifying information about a single member. The class Class supports reflection by including a number of convenience methods by which means you might discover and use type information at runtime. Reflection is also a useful tool for dynamically extracting information about a class, for example to reveal the entire interface including inherited and overridden methods. Here is a nifty little tool that uses reflection to automatically reveal information about a class at runtime. You can run this tool on any class to save you time from having to trawl through endless lines of documentation:- package runtime.types.java; import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.util.regex.Pattern; public class InterfaceLookup {     private static Pattern packageNames = Pattern.compile("\\w+\\.");      public static void showInterface(Object ref) {         try {             Class<?> whichClass = Class.forName(ref.getClass().getName());             Constructor[] constructors = whichClass.getConstructors();             Method[] methods = whichClass.getMethods();             for(Constructor aConstructor : constructors)                 System.out.println(packageNames.matcher(aConstructor.toString())                                   .replaceAll(""));             for(Method aMethod : methods)                 System.out.println(packageNames.matcher(aMethod.toString())                                   .replaceAll(""));         } catch(ClassNotFoundException exceptionRef) {             System.out.println("Class does not exist!");         }     }     public static void main(String[] args) {         showInterface(new InterfaceLookup());     }}/* Outputpublic InterfaceLookup()public static void main(String[])public static void showInterface(Object)public final native void wait(long) throws InterruptedExceptionpublic final void wait(long,int) throws InterruptedExceptionpublic final void wait() throws InterruptedExceptionpublic boolean equals(Object)public String toString()public native int hashCode()public final native Class getClass()public final native void notify()public final native void notifyAll()*// The example uses the forName() to return a reference to the current class and then uses convenience methods to return an array of constructors and methods which it can then iterate through and print out individually. The output is the result of using a regular expression to replace class name qualifiers. This is a quick and easy way to find out all you need to know about a class's interface while coding. As part of it's reflection mechanism, Java also provides classes and interfaces by which means you might implement dynamic proxies which are modeled on the Proxy design pattern. Proxy is a pattern that allows you to provide a surrogate or placeholder for another object in order to control access to it. This is useful in circumstances where you wish to differ the full cost of an objects creation until you actually need it or if you wanted to provide for additional operations you do not wish to be a part of your main object. For instance, consider a drawing application that renders graphics on screen in a scenario where drawing an image is a costly operation you only want to undertake when necessary. You can implement an image proxy between the Image and the calling client so that you can control when and how you create an Image. The following code provides a better illustration:- package runtime.types.java; interface Graphic { void draw(); } class Image implements Graphic {     public void draw() {         System.out.println("Hello!");     }}class ImageProxy implements Graphic {     private Graphic anImage;     public ImageProxy(Graphic args) {         this.anImage = args;     }     public void draw() {         System.out.println(""Calling Image.."");         anImage.draw();     }}public class DrawingApplication {     public static void drawImage(Graphic aGraphic){         aGraphic.draw();     }     public static void main(String[] args) {         drawImage(new ImageProxy(new Image()));     }}/* Output"Calling Image.."Hello!*// The benefits of such a design may not be immediately obvious, however, it does provide us with additional options for instance, we can easily add code to the image proxy to keep track of calls to the Image or to measure the overhead of such calls. Java provides classes to implement a proxy instance that will handle method calls dynamically through the use of an InvocationHandler interface. We can re-implement our image proxy to act as an invocation handler like so:- package runtime.types.java; import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy; class AnotherImageProxy implements InvocationHandler {     private Graphic anImage;     public AnotherImageProxy(Graphic args) {         this.anImage = args;     }     public Object invoke(Object proxy, Method aMethod, Object[] args) throws Throwable {         System.out.println(""Calling Image.."");         return aMethod.invoke(anImage, args);     }}public class AnotherDrawingApplication {     public static void drawImage(Graphic whichImage){         whichImage.draw();     }     public static void main(String[] args) {         Graphic proxy = (Graphic)Proxy.newProxyInstance(Graphic.class.getClassLoader(),                               new Class[]{Graphic.class}, new AnotherImageProxy                                (new Image()));         drawImage(proxy);     }}/* Output"Calling Image.."Hello!*// In this example, we implement the code>invoke() method which is responsible for processing a method invocation on a proxy instance and returning the result, which in this case happens to be a Method object used to invoke the underlying method which it represents. In the main() a proxy instance is returned using the static newProxyInstance() method which accepts a class loader, an array of interfaces to be implemented and the implemented invocation handler, which is handed the Image object as a part of its constructor. In this case it's probably easiest to pass an existing ClassLoader like the Graphic.class reference. RTTI opens up a whole new world of programming possibilities as you come to understand how types provide you with backdoor access into pretty much any interface regardless of access permissions. For instance, consider the following simple interface in the Interfaces.java package:- package Interfaces.java; public interface AnInterface {     void interfaceMethod();} Suppose you wanted to hide the implementation of this interface to deter your customers from relying on it so that you might be free to change it at a later stage? You might think it is enough to restrict the implementation to package access thereby making it inaccessible to clients outside of the package like so:- package runtime.types.java; class HiddenImplementation implements AnInterface {     private String aField = "Can't touch this";     public void interfaceMethod(){ System.out.println("public HiddenImplementation.interfaceMethod()"); }     public void aMethod(){ System.out.println("public HiddenImplementation.aMethod()"); }     void bMethod() { System.out.println("package HiddenImplementation.bMethod()"); }     private void cMethod() { System.out.println("private HiddenImplementation.cMethod()"); }     protected void dMethod() { System.out.println("protected HiddenImplementation.dMethod()"); }      public String toString(){         return aField;     }}public class PublicInterface {     public static AnInterface makeAnInterface() {         return new HiddenImplementation();     }} The PublicInterface class produces an implementation of AnInterface and is the only visible part of this package and you would expect your implementation to be fairly safe? Not exactly, I'm afraid. With reflection, anyone who knows the name of your class members can easily get around this restriction like so:- import java.lang.reflect.Field;import java.lang.reflect.Method;import Interfaces.java.AnInterface;import runtime.types.java.*; public class HackImplementation {     static void hackInterface(Object anObject, String member) throws Exception {         if(member.equals("aField")) {             Field whichField = anObject.getClass().getDeclaredField(member);             System.out.println(anObject.toString());             whichField.setAccessible(true);             whichField.set(anObject, "Yes I can");             System.out.println(anObject.toString());             } else {                 Method whichMethod = anObject.getClass().getDeclaredMethod(member);                 whichMethod.setAccessible(true);                 whichMethod.invoke(anObject);            }     }     public static void main(String[] args) throws Exception {         AnInterface newInterface = PublicInterface.makeAnInterface();         newInterface.interfaceMethod();         //Compile error aField can not be resolved         //!newInterface.aField;         //Compile error method undefined for type AnInterface         /* newInterface.aMethod();            newInterface.bMethod();            newInterface.cMethod();            newInterface.dMethod();         */         hackInterface(newInterface, "aField");         hackInterface(newInterface, "aMethod");         hackInterface(newInterface, "bMethod");         hackInterface(newInterface, "cMethod");         hackInterface(newInterface, "dMethod");     }}/* Outputpublic HiddenImplementation.interfaceMethod()Can't touch thisYes I canpublic HiddenImplementation.aMethod()package HiddenImplementation.bMethod()private HiddenImplementation.cMethod()protected HiddenImplementation.dMethod()*// The example demonstrates how reflection allows you to get around all sorts of restrictions to access and change any field even those marked private and call just about any method no matter the level of the access specifier. With the setAccessible() method you can modify fields and invoke methods, including even those within inner and anonymous classes, are still accessible with reflection. Even if you try to avoid this by distributing only compiled code so that your members are inaccessible, that is still not entirely the case as Java's class file disassembler (javap) can still be used to reveal all your class members. For instance the -private flag can be used to indicate that all members should be displayed including private ones. Running the following command will reveal everything you wish to know about our hidden class. javap -private HiddenImplementation In reality, hardly anything is hidden from reflection and most are susceptible to change, with the exception only of fields marked final. On the flip side if you choose to misuse reflection in your program, committing all sorts of access violations, then you really will only have yourself to blame if a subsequent update to your library succeeds in breaking your code, which I am certain will be a very unpleasant experience Reflection gives you the keys to a new whole new world of dynamic programming in which having access to runtime type information allows for a very different style of programming with which it is easy to get carried away. It is important to remember to use RTTI and reflection in a way that is not detrimental to polymorphism as the most effective way to provide for extensibility in your programs.

Posted by on 21 April 2014 | 7:15 pm

Tonya's Java Journey, Pt. 2

Oracle User Group Norway - Spring Seminar The OUGs are not the typical place for Java developers or community managers (namely me) to be. But OUGN has been working hard to build out a decent Java track with very good speakers, and it was a chance to see how the broader Oracle community is working together when it comes to Java. Also, I was in the neighborhood, more or less, and had never been on a cruise ship. The Spring Seminar is another special conference venue. After leaving Phantasialand and JavaLand, this conference is held on a cruise ferry going from Oslo, Norway to Kiel, Germany and back while keynotes, sessions, networking and fun are ongoing. The Venue The M/S Color Magic is a 735 feet long and nearly 115 feet high ferry which can carry up to 2.700 people in it's 1016 cabins, plus 550 cars. It's BIG, and features, shopping, clubs, dancing, shows, and restaurants. Level 12 is the conference deck with rooms of different sizes and some exhibition space, along with a small catering area which holds food and coffee all day. One leg of the trip took over 20 hours, which equaled enough time to fit everything in that the ship had to offer. With roughly 400 conference attendees there was still a significant number of civilians on board, leading to an...er...interesting mix of people and faces. The Sessions and Speakers With more than 60 sessions the speaker number is basically the same number as JavaLand, but for half of the number of attendees. This made it more difficult to pick the right schedule. While there was an exclusive feel when it comes to well known names in the Oracle sphere, the sessions were sometimes a little too empty. Having the opportunity to speak to Bryn Llewellyn, Cary Millsep, Kellyn Pot'Vin and many more, and listen to Oracle's Andrew Sutherland (Senior Vice President, Oracle EMEA) in this very closed setting made for a completely new experience for me. The Java Track this year was the second try to bring on more Java interested attendees. Starting with Arun Gupta last year, this year we hade Bruno Borges (Oracle), Aslak Knutsen (Red Hat) and Markus Eisele (Java Champion and ACE Director) as the main acts for the Java track. As I said earlier, some of these sessions were attended by only one or two people, which was the loss of those who didn't participate. It was a very personal way of connecting with popular speakers who are used to speaking in front of larger crowds. Questions were answered on a 1:1 basis, and occasionally prepared sessions were thrown aside in favor of direct coaching. The Oracle product-based schedule wasn't up my alley, but the quality of the names and the talks made a very good impression. Feeling and Mood Honestly, this conference was kind of a party. The enclosed space, mix of conference attendees and civilians, and opportunities to carouse lent itself to a jocular atmosphere. Most of the same faces I saw studiously attending sessions were at the disco later that night, loosening their ties and dancing until dawn. I think in a small conference like this there's more of a bonding experience, even though I found my biggest language gap to date. I met fewer people, but felt I really got to talk to them, and know them professionally and personally. Let's do it again next year! xxx More Resources http://www.ougn.no/invitation-english https://www.facebook.com/OracleUsers http://ougnvarseminar2014.sched.org/

Posted by on 21 April 2014 | 3:38 am

Tonya's Java Journey, Pt. 1

Inaugural JavaLand in Germany It took trains, planes, and automobiles to get there. I had heard Germany ran some great conferences, but JavaLand was promised to be outstanding. Kevin already did an interview with one of the organizers, Markus Eisele, about why JavaLand is different. (https://weblogs.java.net/blog/editor/archive/2014/03/01/java-conferences...) But, I got to see first-hand if they deliver. The main conference took place on 25th and 26th of March in Bruehl, Germany, located near Cologne. The conference claimed to be THE event created by the Java community for the Java community. But what they meant by that became much clearer immediately upon arrival. The German JUG umbrella iJUG e.V. (http://www.ijug.eu/en/ijug-verbund/associations-structure.html) was invited by the organizers to contribute in many different ways. The Venue Coming in from a lengthy flight always makes me appreciate getting to the hotel. But anything I typically expected was turned upside down. The venue is a conference center inside a theme park with two theme hotels attached (Africa/Chinese). Everything was exclusively available for the attendees during the two days, and the limited number of rooms let me run into the first speakers and attendees before I'd finished checking in. The conference center inside the main park was the heart of everything. An extensive community hall gave plenty of room for things like hackergarden, nighthacking or adopt-a-jsr sessions. Session rooms were mainly on the first level. with the 4D theater ("Schauspielhaus") and the real theater ("Wintergarten") were used as bigger session rooms. The Schedule and Speakers The schedule contained 65 sessions split over different tracks. It was 95% German-speaking, but offered at least one English-speaking slot for every time of the day. Some of the speakers were internationally known names from Red Hat, Oracle and others. Even if the content was amazing, it was difficult for non-native Germans to follow along with all of it. No recordings of the sessions this year, so all we have is the (overwhelmingly positive) feedback from the attendees and speakers. Java 8 Launch Event At the evening of the 25th, Oracle hosted the official Java 8 launch with Mark Reinhold, Brian Goetz and others. The broadcast made it all the way across the pond to Germany and was streamed live to more than 300 interested attendees via Stephen Chin's nighthacking.com website. The special value add-on was the local panel with Gerrit Grunwald, Paul Backer, Simon Maple, David Blevins and Simon Ritter. They took the opportunity to comment on the stream, while telling the attendees about their own thoughts and experiences. The complete recording is available at http://nighthacking.com/java-8-launch-party-at-javaland/ Feeling and Mood The Community Hall was amazing, plenty of room, tables and chairs, network, powerlines for you to hack, code, work or just hang out with friends. And, can I just mention that the food was AMAZING? The best I've had at any conference, no contest. It was also interesting to see the community hall still full of people once the different rides opened in the evening. There always was an interesting crowd to talk to, and everybody seemed to feel very comfortable. I'll leave you with the impressions from my favorite roller coaster, Black Mamba: http://nighthacking.com/java-8-javaland-roller-coaster/ Thanks for having me ... xxx More Resources Some video-impressions can be found at youtube and cover interviews from Andrew Lee Rubinger, Simon Ritter, Stephen Chin and others giving first feedback about the conference. https://www.youtube.com/user/doagtv/videos Also all nighthacking interviews can be found http://nighthacking.com/category/video/ Two nice picture galleries from Joachim and Alexander give a broader overview about the two amazing days. http://joachim.weinbrenner.name/2014/03/27/impressionen-von-der-javaland... https://www.flickr.com/photos/aheusingfeld/sets/72157643013287384/

Posted by on 20 April 2014 | 9:32 am

A Trio of Java 8 Polls

The past two completed Java.net polls and the current poll all celebrate the formal release of Java 8. The first poll asked for your view of the significance of Java 8, while the second poll asked when you plan to download Java 8. A total of 262 votes were cast in the first poll, which completed two weeks ago. The exact question and results were: How significant is the Java 8 release? 21% (55 votes) - It's the most significant Java release ever 35% (91 votes) - It's among the most significant Java releases ever 29% (76 votes) - It's an important major release 6% (17 votes) - It's a typical Java major release 6% (17 votes) - It's not all that significant, really 2% (6 votes) - Other So, a majority of the voters (56%) consider Java 8 to be one of the most significant Java releases ever, or the most significant release. Adding in the third option, we can say that 85% of the voters consider Java 8 to be an important major release. A further 6% consider Java 8 to be a "typical" major release, while 6% consider Java 8 not to be all that significant. Meanwhile, 6 voters found none of the choices to represent their view of Java 8's significance, but none of them chose to post a comment describing their view. So, if a large majority considers Java 8 an important release, how quickly are people downloading Java 8? For that, we look at the results of the second poll. [Note: Java.net polls are not scientific.] There were 301 votes cast in the second poll, which completed earlier today. The exact question and results were: How soon will you download Java 8? 36% (107 votes) - I'm already working with Java 8 28% (83 votes) - I've downloaded Java 8, but haven't done much with it yet 14% (43 votes) - I'll probably download Java 8 in the next few weeks 10% (31 votes) - Probably some months from now 6% (16 votes) - Before Java 9 comes out 3% (10 votes) - I'm not interested in Java 8 3% (9 votes) - Other Just under 2/3 of the voters (64%) say they've already downloaded Java 8, and a surprising majority of these say they are already working with it. Another 24% expect to download Java 8 within the coming weeks or months. By the time Java 9 comes out, 94% of the voters indicate they will have downloaded Java 8. Of the remaining 6%, half state that they have no interest in Java 8, and the other half selected "Other." pjmlp posted a comment that I'd think applies to a great many Java/JVM developers: I downloaded it, but I don't have any hopes to use it at work for the time being. Recently I joined a new greenfield project that makes use of Java 6 as their target version. The poll didn't distinguish between downloading Java 8 for work or out of curiosity. But it would be surprising if the percentage of developers using Java 8 at work was significant so soon after the formal release. New poll: Java 8 new features Our current poll also has a Java 8 focus. The poll asks: What's the most important new feature in Java 8? Voting will be open until Friday, May 2. What Java.net poll would you like to see? If you have a poll idea, get in touch with me by commenting on this blog post, or by sending an email to editor _at_ java.net, or by using our Submit Article/Blog form. Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham)

Posted by on 18 April 2014 | 10:56 am

Oracle Gathers Together Java 8 Launch Materials: 35 In-Depth Sessions to Date

If you missed the Java 8 Launch Live Webcast, or if you'd like to re-review the webcast, or if you'd like to view more in depth presentations about specific areas of Java 8 (including Java SE 8, Java SE Embedded 8, Java ME 8, and the Internet of Things and The Enterprise) -- then, you'll want to visit the Java 8 Launch site that Oracle has put together. The site is an excellent collection of Java 8 reference materials, including the Java 8 Launch Live Webcast. For example, 12 Java SE 8 sessions are available: Brian Goetz: Java SE 8—Language and Library Features Stephen Colebourne: A New Date and Time API—JSR-310 Paul Sandoz: JDK Hacker on Core Libraries Stuart Marks: Introduction to Lambda Expressions Alex Buckley and Michael Ernst: Enhanced Metadata—Annotations and Access to Parameter Names Staffan Friberg: Performance Improvements in JDK 8 Jim Weaver: What's New for JavaFX in Java SE 8 Simon Ritter: New Features in Java SE 8: A Developer's Guide Geertjan Wielenga: NetBeans IDE 8: Toolbox for Java SE 8 Jim Laskey - Nashorn: JavaScript on the JVM Milton Smith: Java 8 Security Highlights Marcus Hirt: Introducing Java Mission Control 5.3.0 In addition, the site features 8 Java SE Embedded 8 sessions; 10 Java ME 8 sessions; and 5 Internet of Things and The Enterprise sessions. Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham)

Posted by on 14 April 2014 | 5:58 pm

Raspberry Pi and the Internet of Things (IoT) Revolution

Recently I was wandering the aisles of a Barnes and Noble bookstore (the last big chain bookstore in the United States), and I was surprised to see a selection of 6 or 7 books about the Raspberry Pi! Perhaps this shouldn't have surprised me, but it did. Just now, I went to the Barnes and Noble web site and searched for "Raspberry Pi" books, and 70 books were returned, all of them genuinely about the actual hardware Raspberry Pi. Does this surprise you? I think part of my surprise is that some of the first professional programming I did, back in the early 1980s, was developing data acquisition and instrument control software, writing software on $35000 Hewlett-Packard 9845 computers to control custom made boards and other devices over GPIO and RS-232 interfaces. I worked with stepper motors, digitizers, and a slew of other instruments and devices, assisting the U.S. Navy in testing existing and designing new transducers and sonar arrays. That experience left me with the thought that controlling devices was a very expensive endeavor -- which it was back then. But, times change, and they have certainly changed a lot in the past 30+ years with respect to computers, sensors, instruments, and boards that can control hardware like stepper motors. If you look at the basic layout of a Raspberry Pi, you've got a device that is actually much more powerful than most of the equipment I was working with in the early 1980s. For example, that $35000 HP-9845 had a 16-bit CPU running at 5.7 MHz, and it had a base RAM of 24 kBytes (with addition of another 48 kBytes possible). Today's $35 Raspberry Pi runs at 700 MHz and features 512 MBytes of RAM. So, let's do the math: today, for 1/1000 of the cost of an HP-9845, you can get a processor that runs 123 times as fast, and has 21 times as much base RAM. Or, looking at it another way, a $35 Raspberry Pi can do the same processing that would have required 123 HP-9845s in the early 1980s. And those 123 HP-9845s would have cost more than $4.3 Million! That means that the cost of a unit of processing, using the HP-9845 and the Raspberry Pi as the comparative hardware, has fallen by 99.999% over the past three decades. Considering these facts alone, doesn't this imply a revolution of some type? Clearly, the revolution has already happened with respect to computers that can control devices and access sensors. It used to take a big government contract for me to be able to play with devices, control motors, automate research and development processes, etc. Today, a 12 year old who does yard work for the neighboring families can afford equipment that's far more powerful than what I was working with back then. Some people think the Internet of Things (IoT) is just a gimmick, just a fad. No -- when the cost of something useful is reduced by 5 orders of magnitude, something big is going to come out of that. Let the real IoT revolution begin! Watching this is going to be fun. Participating in it (as I plan to do) will be even more fun! Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham) AttachmentSize RaspberryPiSml.jpeg65.31 KB RaspiModelB-diagramSml.png47.28 KB

Posted by on 3 April 2014 | 2:36 pm

Measuring Software Reuse and Deleting Code

This a fun story rather than a deep technical discussion of some performance issue, measure or tool. My memory was jogged by a story (http://www.folklore.org/StoryView.py?story=Negative_2000_Lines_Of_Code.txt) in which Bill Atkinson reported producing -2000 lines of code on his weekly productivity report and by Kevlin Henney retweeting one of my one liners, features are the asset, code is a liability. Needless to say management wasn't impressed by having Bill report that he produced -2000 lines of code. Coders main purpose is to code and if they are producing code you should be able to count how many lines of code they've produced and consequently measure productivity. The key point is that in the process of eliminating code Bill was making the software better and faster. His story reminded me of a situation that I was in 1996. I sat down to have lunch with my supervisor and he hit me with the question, how would you measure reuse. I jokingly answered with 3 questions; what number do you need, who’s bonus depends upon it and how much of that do I get when I come up with that number. It was the look that I got from my supervisor that told me this was a serious question. Apparently the CIO had been sold and then sold a bill of (reuse) good the company we worked for. All projects were being developed in Smalltalk using OO techniques because one of the biggest benefits would be software reuse (read cheaper to build). Indeed, the CIO’s bonus was dependent upon us hitting a certain reuse target. Time to get serious as we had to come up with a way to measure reuse. I started trolling the literature. I read article after book after article that all talked about reuse. The made wild claims of 80%, 90%, even 99.999% reuse! I swear someone would have published a 2000% reuse number if they thought no one would call them out on it.. it was that bad. I say this because out of all the publications that mentioned how much reuse they got on a project, *every single* one of them failed to mention how they managed to come up with this number. I repeat, as incredible as it sounds, not a single article talked about how to actually measure reuse! After much searching about I finally ran into this gem (http://www.amazon.com/Object-Oriented-Software-Metrics-Mark-Lorenz/dp/01...) and after reading it and a few other bits on software metrics I came to the conclusion that the reason we want reuse is to save effort. Effort in writing the code, testing the code, debugging the code, maintaining the code. The benefits come from many directions and the costs seemed to be mainly limited to the effort needed to learn how to use the code. So to measure reuse we should measure of effort saved. Of course this required that we started measuring tons of things that no one in the organization or any organization for that matter ever measured so that we could estimate the effort required to write something from scratch. Since bonus time was coming up fairly shortly it was obvious this turkey wasn’t going to fly. At this point was when Bob Moore, the cleverest guy in our group, stepped in and together we came up with a metric that unfortunately included lines of code as part of the measure. I can’t recall the exact details of the calculation but I do recall that it yielded two numbers, some what similar to what you get from a blood pressure measurement. Of course management wanted a single number and to comply we performed the equivalent of dividing systolic by diastolic pressure to produce a management friendly single number that made absolutely no sense what so ever. My complaint was that as our group improved the frameworks that other groups were “reusing” the reuse number was going to drop. The supervisor thought that this was a ridiculous idea and so unlikely that it didn’t matter anyways. As luck would have it, a month or so laster I was asked to port a piece of our messaging system and in the process I eliminated about 60% of the code base and since that affected the LOC count portion of our “formula” and since *every* project in the company used this messaging framework everyone’s reuse number took a serious hit. By that time I believe the CIO had gotten rid of the reuse target as part of his bonus so no one cared and the project (sensibly) died shortly after that. All I can say is that we all knew it was a silly exercise going into it and in retrospect all that came out of it was this silly story about yet another ridiculous attempt to measure developer productivity.

Posted by on 2 April 2014 | 8:26 am

What is a MEAP? A Video Tutorial + 38% off all MEAPs from manning.com

"What is a MEAP?" - is a video tutorial from Manning Publications. The video can be found here: http://youtu.be/N_CRbc-h0A0 What's a MEAP? We believe you shouldn't have to wait to start learning. In MEAP, the Manning Early Access Program, you read books as they're written. We'll send you new chapters and updates, and you'll get the final eBook the instant it's ready. If you pre-order the pBook, it ships to you weeks before it's available in stores. Check out the new and recently-updated MEAPs. To save 38% on this and all other MEAPs, just enter Promotional Code youtube38 in the Promotional Code box when you check out at manning.com

Posted by on 2 April 2014 | 5:55 am