Saturday, April 14, 2012

Native Modifier

The native Modifier : In java applications, sometimes we will want to use a method that exists outside the JVM. In this scenario, the native modifier can help, native modifier can only apply to a method. Just as the abstract keyword, the native keyword indicates that the implementation of the method exists elsewhere. In case of abstract, the implementation of a method may exist in a subclass of the class in which the abstract method is declared. 

But in the case of native, the implementation of the method exists in a library outside the JVM. The native method is usually implemented in a non-Java language such as C or C++. Before a native method can be invoked, a library that contains the method must be loaded and that library is loaded by making the following system call:


To declare a native method, precede the method with the native modifier, but do not define any body for the method. For example:

public native  void Nativemethod() ;

After you declare a native method, you must write the native method and follow a complex series of steps to link it with your Java code. For example, the following code fragment presents an example of loading a library named NativeMethodDef which contains a method named NativeMethod():

Java Tutorialslass NativeModifierExample
       native void NativeMethod();
Note that the library is loaded in a static code block which suggest that the library is loaded at the class load time, so it is there when a call to the native method is made. One can use the native method in the same way as we use a non-native method. For example, the following two lines of code would invoke the native method,

NativeModifierExample obj = new NativeModifierExample();

Sunday, April 8, 2012

Marker Interface

Marker interface is used as a tag to inform a message to the java compiler so that it can add special behavior to the class implementing it. Java marker interface has no members in it.

Lets take the marker interface. It doesn’t has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the marker interface. In such way, we are intimating the java compiler.

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

We cannot create marker interfaces, as you cannot instruct JVM to add special behavior to all classes implementing (directly) that special interface.

Java Marker Interface Examples

  • java.lang.Cloneable
  • java.util.EventListener