Tuesday 2 October 2012

Java Jinx: Differentianting Java API classes from other classes

This article is about how to differentiate Java API classes from other (external API) classes. This will require a bit of history in why Java became so popular and some architectural background about it. Java was mainly designed to work across networks. Main advantage of Java is that once complied, it could run anywhere, so computers connected across networks can play around with the complied Java file and run them directly on their computer. This led to popularization of Java over networks.

But with networks, comes security. So, any Java code coming through the network ran in a Sandbox, and all the classes that were loaded during the execution of the code went through a security check. The classes are loaded using a Class Loader instance, which performs all the required checks before loading any malicious files. But, these checks take time. So, a Primordial Class Loader loads all classes that are part of the Java API to speed up the loading process. Hence all Java API classes are loaded using the Primordial Class Loader and do not have a Class Loader instance.

So the logic is this: take any classes and check its ClassLoader instance exists using the getClassLoader() method, if the value is null, it is a class from an in-built Java API, otherwise, it is a class from external API, not part of Java API bundle.

Here is the code snippet demonstrating the use:
import org.codehaus.jackson.map.ObjectMapper;

public class ClassSourceInfo {

public static void main(String[] args) {
Integer a = new Integer(10); //any Java API class
ObjectMapper mapper = new ObjectMapper(); //any external API class

determineClassSource(a.getClass());
determineClassSource(mapper.getClass());
}

private static void determineClassSource(Class clazz) {
if(clazz.getClassLoader()==null)
System.out.println("Class is part of Java API");
else
System.out.println("Class is not part of Java API");
}
}
Now the question comes, where is this useful. Well, that is for programmers to decide. For example, there can be a scenario where every class which belongs to an external API used in the Production Code be logged into a file, just for debugging purposes.

No comments:

Post a Comment