Showing posts with label java6. Show all posts
Showing posts with label java6. Show all posts

Sunday, 3 July 2011

Wildcard in Java classpath

One of the less known new features of JDK 6 is the ability to use wildcards in classpaths.
That means that instead of doing…
java -cp lib\x.jar;lib\y.jar;lib\z.jar; com.company.MyProggy
…you could just do…
java -cp lib\*.jar; com.company.MyProggy
That generally turns out to be quite a time saver. Especially so if you are trying out something at a remote box and vi is your only editor.
However, if you use the wild card, there is no way to predict the order in which the jars will be used. In some cases, the order is important – and in those cases, you will need to add in the jars like one normally does by enumerating each one explicitly.
Also, don’t forget the semi colon at the end of the classpath. Sometimes lots of time is lost due to this. It can be really frustrating!

Saturday, 11 June 2011

String empty check is more easy now with JDK6 and StringUtils

Prior to JDK 6, we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)

//OR

if(("").equals(s))

Support from JDK6
Checking its length is more readable and may be a little faster. Starting from JDK 6, String class has a new convenience method isEmpty():

boolean isEmpty()
Returns true if, and only if, length() is 0.

It is just a shorthand for checking length. Of course, if the String is null, you will still get NullPointerException.
I don't see much value in adding this convenience method. Instead,
I'd like to see a static utility method that also handle null value:

public static boolean notEmpty(String s) {
return (s != null && s.length() > 0);
}



Support from StringUtils
Another option, use StringUtils.isEmpty(String str) of Apache commons , can be downloaded from - http://commons.apache.org/

It checks for null string also and return true for empty
public static boolean isEmpty(String str) {
return str == null str.length() == 0;
}


Monday, 23 May 2011

ConcurrentSkipListMap Class in java Collections

ConcurrentSkipListMap is one of the class which implements NavigableMap.
This class implement all of the optional methods of the Map and Iterator interfaces. Like most other concurrent collections, this class does not permit the use of null keys or values because some null return values cannot be reliably distinguished from the absence of elements. NavigableMap class is similar to NavigableSet. In NavigableMap we use methods to return the key value pair like navMap.put(1, "sunday") whereas in NavigableSet we use methods to return values.

Example:

NavigableMap navmap=new ConcurrentSkipListMap();
navmap.put(1, "Sunday");

navmap.put(2, "Monday");

navmap.put(3, "Tuesday");

navmap.put(4, "Wednesday");

navmap.put(5, "Thursday");

navmap.put(6, "Friday");

navmap.put(7, "Saturday");

//Retrieving first data
String first = navmap.firstEntry();
//Retrieving last data
String last = navmap.lastEntry();
//Retrieving the nearest less than or equal to the given key
String closeFloorKeyVal = navmap.floorEntry(5);
//Retrieving the greatest key strictly less than the given key
String less = navmap.lowerEntry(3);
//Retrieving a key-value associated with the least key
//strictly greater than the given key
String higher=navmap.higherEntry(5);
//Removing first
String remFirst = navmap.pollFirstEntry();
//Removing last
String remLast = navmap.pollLastEntry();



ConcurrentSkipList class in java

There are two new interfaces in Java 6 SE called "NavigableMap" and "NavigableSet" which facilitate navigating through collections. NavigableSet extends SortedSet and is implemented by TreeSet and concurrentSkipListSet (a new class in Java collection).
ConcurrentSkipListSet is one of the class that implements NavigableSet and it is used to return the closest matches of elements. It includes methods to return iterators in ascending and descending orders, as well as methods that return a sorted or navigable set for a special portion of data.

NavigableSet nset = new ConcurrentSkipListSet();

nset.add("20");

nset.add("60");

nset.add("50");

nset.add("40");

nset.add("30");

nset.add("80");
// Returns an iterator over the elements in navigable set,
//in ascending order.
Iterator iterator = nset.iterator();

//set in ascending order

while (iterator.hasNext())

{ //Ascending order list

System.out.print(iterator.next() + " ");

}

//Descending order list

System.out.println("In descending order : " + nset.descendingSet() + "\n");
//remove element
nset.pollLast();

Wednesday, 13 April 2011

Programmatic Compilation with Java

Till date we all know that Java compilation is not a runtime business. Write code, compile and generate byte code, deploy and run it on any jvm. But this restriction is removed from java 6. Now compilation is no more a pre-runtime business. Using APIs provided by java 6, we can generate classes runtime and compile to generate class files, which can be used further.Let us see the important classes we need in writing a programmatic compiler.

javax.tools.Diagnostic: Helps to receive compilation results.

javax.tools.DiagnosticListener: Listener can be configured to receive diagnostic results. If there is no listener configured then results will be delivered through System.err.

javax.tools.JavaCompiler: These compilers will be invoked from program. One of the implementation will be used to do the job.

javax.tools.CompilationTask: Does actual compilation business.

javax.tools.JavaFileManager: It manages the source and class files.

javax.tools.JavaFileObject: Represents source and class files.

There are multiple implementations of these interfaces which serve specific purpose. Let us take a look at an example and understand the details.

In this example, we write two classes.

TestClass.java: This is the class to be compiled.

CodeCompiler.java: Does the compilation business.

In addition to this we have one more task. Let us check if the generated class file has three methods overridden – equals, hashCode and toString. Our coding standard expects this in all classes. Here also we take support of javax.tools package.

TestClass.java

public class TestClass {

public static void main(String[] args) {
TestClass testClass = new TestClass();
testClass.processString("String");
}

private void processString(String str){
for(int count=0; count<10;count++){
String myStr = "";
myStr = str;
}
System.out.println("Finished." + str);
}
}

 

CodeCompiler.java

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
import sun.tools.java.ClassFile;

public class CodeCompiler {

public static void main(String[] args) {
try{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(
null, null, null);
Iterable compilationUnits1 = fileManager
.getJavaFileObjects("D:\\TestClass.java");
CompilationTask task = compiler.getTask(null, fileManager, null, null,
null, compilationUnits1);

// Perform the compilation task.
task.call();
fileManager.close();
ClassFile cf = new ClassFile(new File("TestClass.class"));
validateDefaultMethods(cf);

}catch(IOException ioe){
ioe.printStackTrace();
}
}

protected static void validateDefaultMethods(ClassFile clazzInfo) {
boolean hasEquals = false;
boolean hasHashCode = false;
boolean hasToString = false;
for (Method method : clazzInfo.getClass().getMethods()) {
String methodName = method.getName();
Class[] types = method.getParameterTypes();
if ("equals".equals(methodName) && types.length == 1) {
if ("java.lang.Object".equals(types[0])) {
hasEquals = true;
}
} else if ("hashCode".equals(methodName) &&
types.length == 0) {
hasHashCode = true;
}else if("toString".equals(methodName)&&
types.length == 0){
hasToString = true;

}
}
if(hasEquals&&hasHashCode&&hasToString){
System.out.println("Valid Code");
}else{
System.out.println("Invalid Code");
}
}

}

 

You may have to add tools.jar explicitly to your class path to use ClassFile class.

The class file will be generated in class path with same package structure if the destination is not specified.

What Else Can be Done?

1. Generate a java file on file server and compile it.

2. Generate a java file string and compile it.

3. Generate java files, compile and generate a jar file out of such class files.

4. You can write your own ide using this feature.