This section covers the Checkstyle static analysis tool and how to configure Eclipse with Checkstyle. Checkstyle verifies the following rules:
The Checkstyle plugin can be downloaded from http://sourceforge.net/projects/eclipse-cs/, or you can install it through Eclipse Marketplace. Just search for Checkstyle.
Perform the following steps to configure the Checkstyle Eclipse plugin:
The following screenshot shows the Checkstyle components to be installed:
Now that installation has finished, it's time to examine the Checkstyle capabilities. Create a Java project named CodeQualityChapter06
(create a chapter06
folder under a directory named packt
and save the project in Packtchapter06
), add a Java class named Calculator.java
, and add the following code snippet to Calculator.java
:
package com.packt.code.quality; public class Calculator<T extends Number> { public String add(T... numbers) { T result = null; int x =0; for(T t:numbers) { x++; if(result == null) { if(t instanceof Integer) { result = (T) new Integer("0"); }else if(t instanceof Short) { result = (T) new Short("0"); }else if(t instanceof Long) { result = (T) new Long("0"); }else if(t instanceof Float) { result = (T) new Float("0.0"); }else if(t instanceof Double) { result = (T) new Double("0.0"); } } if(t instanceof Integer) { Integer val = ((Integer)result + (Integer)t); result =(T)val; }else if(t instanceof Short) { Short val = (short) ((Short)result + (Short)t); result =(T)val; }else if(t instanceof Long) { Long val = ((Long)result + (Long)t); result =(T)val; }else if(t instanceof Float) { Float val = ((Float)result + (Float)t); result =(T)val; }else if(t instanceof Double) { Double val = ((Double)result + (Double)t); result =(T)val; } if(x == 1045) { System.out.println("warning !!!"); } } return result.toString(); } }
This class, Calculator.java
, calculates the sum of a list of numbers. It's a generic class; we can calculate the sum of integers or doubles or any number.
Right-click on CodeQualityChapter06
and enable Checkstyle. The following screenshot displays the Checkstyle pop-up menu:
This action will trigger the Checkstyle validation. It will open the Checks tab (if the Checks tab is not opened automatically, then open the view from the show views menu) and show a graphical view of violations. The following screenshot displays the graphical violation pie chart:
Another view shows the violations in a tabular format. The following screenshot displays the violations in a tabular format:
18.221.50.185