Sunday, 31 December 2017

Generating Getters And Setters Using Reflection - Java Program

When you right click on any Java Bean class name with in the eclipse IDE and click on Source – Generate Getters and Setters you get the getter and setter methods for the selected fields. Ever wondered what goes in the background to generate the getter and setter methods?

Yes, it is the magic of reflection in Java which gets the information about the fields of the class and their types and then generate the getters and setters using reflection accordingly.

If you have to create such a functionality yourself then using the reflection API you can create your own getters and setters generator class, of course just for academic purpose, as all the IDEs anyway provide the facility to do that.

Getters & Setters generator using reflection example

Let’s say you have a class TestClass with three fields of type int, String and Boolean and you want to generate getters and setters for these 3 fields using Java reflection API.

TestClass

public class TestClass {

 private int value;
 private String name;
 private boolean flag;
} 

GetterSetterGenerator class

Using the reflection API for the field you can get information about the fields of the given class – like name and type. Once you have that information you can create set and get methods for the fields. In this code set and get methods are just printed after creating them as it is just for illustrating the usage of reflection in Java so not going into File I/O.

import java.lang.reflect.Field;
import java.util.Arrays;

public class GetterSetterGenerator {

 public static void main(String[] args) {
  try {
   GetterSetterGenerator gt = new GetterSetterGenerator();
   StringBuffer sb = new StringBuffer();
   
   Class<?> c = Class.forName("org.prgm.TestClass");
   // Getting fields of the class
   Field[] fields = c.getDeclaredFields();
   System.out.println("Fields - " + Arrays.toString(fields));
   for(Field f : fields){
    String fieldName = f.getName();
    String fieldType = f.getType().getSimpleName();
    
    System.out.println("Field Name -- " + fieldName);
    System.out.println("Field Type " + fieldType);
    
    gt.createSetter(fieldName, fieldType, sb);
    
    gt.createGetter(fieldName, fieldType, sb);
   }
   System.out.println("" + sb.toString());
   
  }catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
 /**
  * @param fieldName
  * @param fieldType
  * @param setter
  */
 private void createSetter(String fieldName, String fieldType, StringBuffer setter){
  
  setter.append("public void").append(" set");
  setter.append(getFieldName(fieldName));
  setter.append("(" + fieldType + " " + fieldName + ") {");
  setter.append("\n\t this."+ fieldName + " = " + fieldName + ";");
  setter.append("\n" + "}" + "\n");
 }
 
 /**
  * @param fieldName
  * @param fieldType
  * @param setter
  */
 private void createGetter(String fieldName, String fieldType, StringBuffer getter){
  // for boolean field method starts with "is" otherwise with "get"
  getter.append("public " + fieldType).append((fieldType.equals("boolean")?" 
    is" : " get") + getFieldName(fieldName) + "(){");
  getter.append("\n\treturn " + fieldName + ";");
  getter.append("\n" + "}" + "\n");
 }
 
 /** 
  * @param fieldName
  * @return
  */
 private String getFieldName(String fieldName){
  return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(
    1, fieldName.length());
 }
}

Output

 Fields - [private int org.prgm.TestClass.value, private java.lang.String org.prgm.TestClass.name, private boolean org.prgm.TestClass.flag]
Field Name -- value
Field Type int
Field Name -- name
Field Type String
Field Name -- flag
Field Type Boolean

public void setValue(int value) {
  this.value = value;
}
public int getValue(){
 return value;
}
public void setName(String name) {
  this.name = name;
}
public String getName(){
 return name;
}
public void setFlag(boolean flag) {
  this.flag = flag;
}
public boolean isFlag(){
 return flag;
}

That's all for this topic Generating Getters And Setters Using Reflection - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Invoking getters and setters using Reflection - Java Program
  2. Reflection in Java - Getting Class Information
  3. Reflection in Java - Getting Method Information
  4. How to Pass Command Line Arguments in Eclipse
  5. How to Compile Java Program at Runtime

You may also like-

  1. How to remove duplicate elements from an array - Java Program
  2. How to format date in Java using SimpleDateFormat
  3. Reading all files in a folder - Java Program
  4. Nested class and Inner class in Java
  5. Externalizable interface in Java
  6. Constructor chaining in Java
  7. Parallel Stream in Java Stream API
  8. Method reference in Java 8

Invoking Getters And Setters Using Reflection - Java Program

In the post reflection in java – method it is already explained how you can invoke a method of the class at runtime. In this post we’ll use that knowledge to invoke getters and setters of the class using Java reflection API. In Java you can do it using two ways.

In this post we'll see example of both of these ways to invoke getters and setters of the class.

Using PropertyDescriptor class

A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods. Then using the getReadMethod() and getWriteMethod() you can call the setter and getter for the property.

Invoking getters and setters using PropertyDescriptor example

Here in the example we have a class TestClass which has getter and setter for three fields which are of type int, String and boolean. Then in the GetterAndSetter class there are methods to invoke the getters and setters of the given class.

TestClass.java

package org.prgm;

public class TestClass {
 private int value;
 private String name;
 private boolean flag;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public boolean isFlag() {
  return flag;
 }
 public void setFlag(boolean flag) {
  this.flag = flag;
 }
}

GetterAndSetter.java

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class GetterAndSetter {
 public static void main(String[] args) {
  GetterAndSetter gs = new GetterAndSetter();
  TestClass tc = new TestClass();
  gs.callSetter(tc, "name", "John");
  gs.callSetter(tc, "value", 12);
  gs.callSetter(tc, "flag", true);
  // Getting fields of the class
  Field[] fields = tc.getClass().getDeclaredFields();
  
  for(Field f : fields){
   String fieldName = f.getName();
   System.out.println("Field Name -- " + fieldName);
  }
  gs.callGetter(tc, "name");
  gs.callGetter(tc, "value");
  gs.callGetter(tc, "flag");
 }
 
 private void callSetter(Object obj, String fieldName, Object value){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   pd.getWriteMethod().invoke(obj, value);
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 private void callGetter(Object obj, String fieldName){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   System.out.println("" + pd.getReadMethod().invoke(obj));
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Field Name -- value
Field Name -- name
Field Name -- flag
John
12
true

Scanning methods of the class and look for set and get methods

Another way to invoke the getters and setters using Java reflection is to scan all the methods of the class through reflection and then find out which are the getters and setters method.

It is particularly useful to use this way to call get methods if you have lots of fields in a class. Calling set method that way won’t be of much help as you will have to still invoke individual method with the value that has to be set.

Logic to identify get method

get method starts with get or is (in case of boolean), it should not have any parameters and it should return a value.

Logic to identify set method

set method starts with set and it should have a parameter and it shouldn't return any value which means it should return void.

Example Code

Same Java bean class as above TestClass is used here too.

GetterAndSetter.java

In the GetterAndSetter class there are methods to identify the getters and setters of the given class. If it is a get method that is invoked to get the value. For set method name of the method is printed.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GetterAndSetter {
    public static void main(String[] args) {
        TestClass tc = new TestClass();
        // Setting values
        tc.setName("John");
        tc.setValue(12);
        tc.setFlag(true);
        
        Method[] methods = tc.getClass().getDeclaredMethods();
        for(Method method : methods){
            if(isGetter(method)){
                try {
                    Object obj = method.invoke(tc);
                    System.out.println("Invoking "+ method.getName() + " 
                     Returned Value - " + obj);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(isSetter(method)){
                System.out.println("Setter -- " + method.getName());
            }
        }
    }
    
    private static boolean isGetter(Method method){
        // identify get methods
        if((method.getName().startsWith("get") || method.getName().startsWith("is")) 
          && method.getParameterCount() == 0 && !method.getReturnType().equals(void.class)){
            return true;
        }
        return false;    
    }
    
    private static boolean isSetter(Method method){
        // identify set methods
        if(method.getName().startsWith("set") && method.getParameterCount() == 1 
          && method.getReturnType().equals(void.class)){
            return true;
        }
        return false;    
    }
}

Output

Invoking getName Returned Value - John
Invoking getValue Returned Value - 12
Setter -- setName
Setter -- setValue
Setter -- setFlag
Invoking isFlag Returned Value - true

That's all for this topic Invoking Getters And Setters Using Reflection - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Generating getters and setters using Reflection - Java Program
  2. Reflection in Java
  3. Reflection in Java - Getting Class Information
  4. Reflection in Java - Getting Field Information
  5. Reflection in Java - Getting Constructor Information

You may also like-

  1. How to Sort elements in different order in TreeSet
  2. Lambda Expression Callable example
  3. How to run a shell script from Java program
  4. Insert\Update using NamedParameterJDBCTemplate in Spring framework
  5. Java Stream API Examples
  6. How to fix the target type of this expression must be a functional interface error
  7. PermGen Space Removal in Java 8
  8. Marker interface in Java

How to Sort an ArrayList in Descending Order in Java

In Java ArrayList elements are added in sequential order and while iterating an arraylist same sequential order will be used to retrieve the elements. Sometimes you may have a requirement to sort an arraylist in ascending or descending order. In this post we'll see how to sort an ArrayList in descending order in Java.

Sorting ArrayList in descending order

For sorting ArrayList in descending order in Java there are two options

  1. Use method reverseOrder() provided by Collections class. See example.
  2. General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  3. Using a custom comparator. See example.

You must also know about the overloaded method sort provided by the Collections class.

  • public static <T> void sort(List<T> list, Comparator<? super T> c) - Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).

Sorting ArrayList Using reverseOrder method

reverseOrder() method mentioned above can be provided as the second parameter in the sort method mentioned above and you will get the ArrayList sorted in reverse order. Let's see an example.

In the program Collections.reverseOrder() method is passed as an argument to the Collections.sort() method to sort ArrayList in reverse order.

public class SortListDemo {

    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, Collections.reverseOrder());
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}

Output

Name Mumbai
Name Mumbai
Name Kolkata
Name Delhi
Name Chennai
Name Bangalore

Sorting Java ArrayList Using custom Comparator

Internally reverseOrder method calls a Comparator class to do the sorting in reverse order. You can do it yourself too by writing your own comparator class. Writing your own Comparator gives you more control over the object ordering.

public class SortListDemo {
    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, new MyComparator());
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}

//Custom comparator class
class MyComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }    
}

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic How to Sort an ArrayList in Descending Order in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. How LinkedList Class Works Internally in Java
  5. CopyOnWriteArrayList in Java - The thread safe variant of ArrayList

You may also like -

  1. How does HashMap internally work in Java
  2. Difference Between CountDownLatch And CyclicBarrier in Java
  3. Phaser in Java concurrency
  4. varargs in Java
  5. What if run() method called directly instead of start() method
  6. static reference to the non-static method or field error
  7. Method overloading in Java
  8. Creating Custom Exception Class in Java

Saturday, 30 December 2017

Reflection in Java - Getting Method Information

Reflection in Java class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class like fields, constructors, methods.


Member Interface in Java Reflection API

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor classes. Thus Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

This post talks about Method class and how it can be used to get information about methods using reflection. Class methods have return values, parameters, and may throw exceptions. The java.lang.reflect.Method class provides methods for obtaining the type information for the parameters and return value. It may also be used to invoke methods on a given object.

How to get Method object

Once you have instance of the Class you can use any of the following 4 methods for getting information about methods of the class.

  • getMethod(String name, Class<?>... parameterTypes)- Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
  • getMethods()- Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
  • getDeclaredMethod(String name, Class<?>... parameterTypes)- Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
  • getDeclaredMethods()- Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Getting method information using Java reflection example

As a preparation for the example code let’s have a class called Parent.java which will be extended by the class ChildClass.java which is the class we are going to examine. There is also an interface IntTest.java which is implemented by ChildClass.java.

Parent class

public class Parent {
 String name;
 Parent(String name){
  this.name = name;
 }

 public void displayName(String name){
  System.out.println("Hello - " + name);
 }
  
 public String getName(){
  return name;
 }
}

IntTest interface

public interface IntTest {
 public void showValue();
}

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
}

Now let’s see how you can get method information using all the four methods mentioned above.

import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectMethod {
    public static void main(String[] args) {
        try {
            // Getting Class instance
            Class<?> c = Class.forName("org.netjs.prog.ChildClass");
            
            // Using getMethod(methodName, parameters)
            Method method = c.getMethod("displayName", String.class);
            System.out.println("Method params " + Arrays.toString(method.getParameters()));
            
            // Will throw exception
            /*method = c.getDeclaredMethod("displayName", String.class);
            System.out.println("Method params " + Arrays.toString(method.getParameters()));*/
            
            Method[] methodArr = c.getMethods();
            System.out.println("All methods " + Arrays.toString(methodArr));
            
            methodArr = c.getDeclaredMethods();
            System.out.println("Class methods " + Arrays.toString(methodArr));
            
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output

Method params [java.lang.String arg0]

All methods [public void org.netjs.prog.ChildClass.showValue(), public java.lang.String org.netjs.prog.Parent.getName(), 
public void org.netjs.prog.Parent.displayName(java.lang.String), 
public final void java.lang.Object.wait() throws java.lang.InterruptedException, 
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, 
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, 
public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), 
public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), 
public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]

Class methods [public void org.netjs.prog.ChildClass.showValue()]

First call to the getMethod with parameters method name and parameter types returns the matching method. Then parameters of the method are printed using the getParameters() method of the Method class.

Second call (Which is commented) will throw NoSuchMethodException as the method displayName is inherited from the parent class and getDeclaredMethod() will work for the methods with in the class.

getMethods() will return all the methods of the class and also the inherited methods.

GetDeclaredMethods() will return all the methods of the class but not the inherited one.

Getting method parameter types and return type using reflection

If we have a class called ChildClass as follows then we can get its method parameter types and return type using reflection.

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
 
 public String getValue(String name) throws Exception{
  return "Hello" + name;
 }

}

Example code

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
    System.out.println("For Method - " + m.getName() + " Parameter types are - " + Arrays.toString(m.getParameterTypes()));
    System.out.println("For Method - " + m.getName() + " Return type " + m.getReturnType());
}

Output

For Method - getValue Parameter types are - [class java.lang.String]
For Method - getValue Return type class java.lang.String
For Method - showValue Parameter types are - []
For Method - showValue Return type void

Getting method modifiers using reflection

If you want to get information about the modifiers of the methods of the class you can use getModifiers() method whose return type is int.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
    System.out.println("For Method - " + m.getName() + 
 " modifier is - " + Modifier.toString(m.getModifiers()));
}

Output

For Method - getValue modifier is – public
For Method - showValue modifier is – public

Getting thrown exceptions using reflection

If you want to get information about types of exceptions declared to be thrown by the methods of the class you can use getExceptionTypes() method.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
    System.out.println("For Method - " + m.getName() + " Thrown Exceptions  - " 
 + Arrays.toString(m.getExceptionTypes()));
}

Output

For Method - getValue Thrown Exceptions  - [class java.lang.Exception]
For Method - showValue Thrown Exceptions  - []

Invoking method using reflection

Using Java reflection API you can also invoke methods on a class at runtime. Methods are invoked using java.lang.reflect.Method.invoke() method. The first argument is the object instance on which this particular method is to be invoked. (If the method is static, the first argument should be null.) Subsequent arguments are the method's parameters.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
// Getting class object
ChildClass ch = new ChildClass("Test", 10);
Method method = c.getDeclaredMethod("getValue", String.class);
try {
    String result = (String)method.invoke(ch, "Reflection");
    System.out.println("Method invocation returned - " + result);
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Output

Method invocation returned – HelloReflection

Invoking private method of the class using reflection

You can even invoke the private method of the class using reflection in Java. Using getDeclaredMethod() you can get even the private method of the class.

Once you have the method object you can use the setAccessible() method which is inherited from class java.lang.reflect.AccessibleObject to set the access for the private method as true at run time and then invoke it from another class.

Let’s say we have a ChildClass as follows with a private method getValue().

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
 
      private String getValue(String name) throws Exception{
  return "Hello" + name;
 }
}

Now you want to invoke this private method.

Example code

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
// Getting class object
ChildClass ch = new ChildClass("Test", 10);
Method method = c.getDeclaredMethod("getValue", String.class);
method.setAccessible(true);
try {
    String result = (String)method.invoke(ch, "Reflection");
    System.out.println("Method invocation returned - " + result);
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Output

Method invocation returned – HelloReflection

You can comment the line where access to the method is set as true.

//method.setAccessible(true);

Then if you execute it you will get the exception as follows -

java.lang.IllegalAccessException: Class org.netjs.prog.ReflectMethod can not access a member of class 
org.netjs.prog.ChildClass with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
 at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
 at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at org.netjs.prog.ReflectMethod.main(ReflectMethod.java:32)

That's all for this topic Reflection in Java - Getting Method Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Field
  2. Reflection in Java - Constructor
  3. Reflection in Java - Array
  4. Generating getters and setters using Reflection - Java Program
  5. Core Java Basics Interview Questions

You may also like-

  1. Externalizable interface in Java
  2. Java Concurrency interview questions
  3. FlatMap in Java
  4. Method reference in Java 8
  5. Wildcard in Java Generics
  6. Race condition in Java multi-threading
  7. Switch-Case statement in Java
  8. static block in Java

Wednesday, 20 December 2017

PriorityBlockingQueue in Java

PriorityBlockingQueue class in Java is an implementation of BlockingQueue interface. PriorityBlockingQueue class uses the same ordering rules as the PriorityQueue class, in fact PriorityBlockingQueue can be termed as the thread-safe alternative of the PriorityQueue as it has blocking retrieval operations.

PriorityBlockingQueue is logically unbounded

While PriorityBlockingQueue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError). That's where it differs from the other implementations of BlockingQueue like ArrayBlockingQueue (Always bounded) and LinkedBlockingQueue (both bounded and unbounded options).

As Example put(E e) method in ArrayBlockingQueue or LinkedBlockingQueue will wait if necessary for space to become available.

Whereas put(E e) method in PriorityBlockingQueue will never block as it is unbounded.

Elements are sorted in Java PriorityBlockingQueue

The elements of the PriorityBlockingQueue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

Note that a priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).

Java PriorityBlockingQueue Constructors

  • PriorityBlockingQueue()- Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
  • PriorityBlockingQueue(Collection<? extends E> c)- Creates a PriorityBlockingQueue containing the elements in the specified collection.
  • PriorityBlockingQueue(int initialCapacity)- Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.
  • PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator)- Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.

Nulls are not allowed in PriorityBlockingQueue

PriorityBlockingQueue in Java does not permit null elements. Trying to add null to the queue results in NullPointerException.

public class PriorityQDemo {

    public static void main(String[] args) {
        BlockingQueue<String> priortyBQ = new PriorityBlockingQueue<String>();
        priortyBQ.add("E");
        priortyBQ.add("B");
        priortyBQ.add("N");
        priortyBQ.add(null);
    }
}

Output

Exception in thread "main" java.lang.NullPointerException
 at java.util.concurrent.PriorityBlockingQueue.offer(PriorityBlockingQueue.java:479)
 at java.util.concurrent.PriorityBlockingQueue.add(PriorityBlockingQueue.java:463)
 at org.netjs.programs.PriorityQDemo.main(PriorityQDemo.java:13)

PriorityBlockingQueue Java example

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityQDemo {

    public static void main(String[] args) {
        String[] cityNames = {"Delhi", "Mumbai", "Chennai", "Bangalore", 
                "Hyderabad", "Lucknow"};
        // initializing PriortiyBlockingQueue
        BlockingQueue<String> priortyBQ = new PriorityBlockingQueue<String>();
        
        // Producer thread
        new Thread(){
            @Override
            public void run() {
                for(int i = 0; i < cityNames.length; i++){
                    try {
                        priortyBQ.put(cityNames[i]);
                    } catch (InterruptedException e) {
                        System.out.println("Error while putting values in the Queue " 
                         + e.getMessage());
                    }
                }
            }
        }.start();
        
        // Consumer thread
        new Thread(){
            @Override
            public void run() {
                for(int i = 0; i < cityNames.length; i++){
                    try {
                        System.out.println(" Consumer got - " + priortyBQ.take());
                    } catch (InterruptedException e) {
                        System.out.println("Error while retrieving value from the Queue " 
                         + e.getMessage());
                    }
                }
            }
        }.start();
    }
}

Output

Consumer got - Bangalore
Consumer got - Chennai
Consumer got - Delhi
Consumer got - Hyderabad
Consumer got - Lucknow
Consumer got - Mumbai

It can be seen here that the city names are ordered.

You can also use a comparator, if you want different ordering than the natural ordering. Here, if you want the cities in reverse order you can use the constructor that takes comparator as parameter.

PriorityBlockingQueue with Comparator Java Example

import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityQDemo {

    public static void main(String[] args) {
        String[] cityNames = {"Delhi", "Mumbai", "Chennai", "Bangalore", 
                "Hyderabad", "Lucknow"};
        // initializing PriortiyBlockingQueue
        BlockingQueue<String> priortyBQ = new PriorityBlockingQueue<String>(10, new CityComparator());
        
        // Producer thread
        new Thread(){
            @Override
            public void run() {
                for(int i = 0; i < cityNames.length; i++){
                    try {
                        priortyBQ.put(cityNames[i]);
                    } catch (InterruptedException e) {
                        System.out.println("Error while putting values in the Queue "
                         + e.getMessage());
                    }
                }
            }
        }.start();
        
        // Consumer thread
        new Thread(){
            @Override
            public void run() {
                for(int i = 0; i < cityNames.length; i++){
                    try {
                        System.out.println(" Consumer got - " + priortyBQ.take());
                    } catch (InterruptedException e) {
                        System.out.println("Error while retrieving value from the Queue " 
                          + e.getMessage());
                    }
                }
            }
        }.start();
    }
}

// Comparator class
class CityComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }    
}

Output

Consumer got - Mumbai
Consumer got - Lucknow
Consumer got - Hyderabad
Consumer got - Delhi
Consumer got - Chennai
Consumer got - Bangalore 

PriorityBlockingQueue Iterator

Note that though elements are stored using natural ordering, Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityBlockingQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

That's all for this topic PriorityBlockingQueue in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. LinkedBlockingQueue in Java Concurrency
  2. DelayQueue in Java Concurrency
  3. BlockingDeque in Java Concurrency
  4. ConcurrentSkipListSet in Java
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. Thread Starvation in Java Multi-Threading
  2. Stream API in Java 8
  3. Serialization in Java
  4. Initializer block in Java
  5. Marker interface in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. interface static methods in Java 8
  8. Different bean scopes in Spring

Friday, 15 December 2017

static Block in Java

Static block in Java is used for static initializations of a class. Consider a scenario where initialization of static variables requires some logic (for example, error handling or a for loop to fill a complex array). In such scenarios, simple assignment is inadequate.

In case of instance variables, initialization can be done in constructors, where exception handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

static Block is Executed Only Once

A static block in a class is executed only once, when the class is first loaded, even before the main method. Note that class can be loaded when you make an object of that class or when you access the static member of that class for the first time.

General form of the Java static block

static{
// whatever code is needed for initialization goes here
}

Example code

public class StaticBlockDemo {
  // static blank final variable
  static final int i;
  static int b;
  //static block
  static {
   System.out.println("in static block");
   i = 5;
   b = i * 5;
   System.out.println("Values " + i + " " +  b);
  }
  
  public static void main(String[] args) {
     System.out.println(" in main method ");
  }
}

Output of the program

in static block
Values 5 25
in main method

It can be seen that main method is called only after executing the static block. In static block the static blank final variable is initialized. Also another static variable too is initialized with in the block after some computation.

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks in Java are called in the order that they appear in the source code.

Since static blocks are used to initialize the class variables so static blocks in Java are called before the constructor of the class.

public class StaticBlockDemo {
  // static blank final variable
  static final int i;
  static int b;
  //static block
  static {
   System.out.println("in static block");
   i = 5;
   b = i * 5;
   System.out.println("Values " + i + " " +  b);
  }
  
  StaticBlockDemo(){
   System.out.println("In constructor");
  }
  
  public static void main(String[] args) {
    System.out.println("in main method ");
    StaticBlockDemo sb = new StaticBlockDemo();
  }
  
  static {
   System.out.println("In another static block");
  }

}

Output

in static block
Values 5 25
In another static block
in main method 
In constructor

Java static block exception handling

static block can throw only RunTimeException, or there should be a try-catch block to catch checked exception.

Example Code

static int i;
static int b;
static {
 System.out.println("in static block");
 try{
  i = 5;
  b = i * 5;
 }catch(Exception exp){
  System.out.println("Exception while initializing" + exp.getMessage());
  throw new RuntimeException(exp.getMessage()); 
}
 //System.out.println("Values " + i + " " +  b);
}

That's all for this topic static Block in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. static in Java
  2. static method overloading or overriding in Java
  3. interface static methods in Java 8
  4. Initializer block in Java
  5. Core Java Basics Interview Questions

You may also like -

>>>Go to Java Basics Page

Sunday, 10 December 2017

Difference Between Array And ArrayList in Java

Difference between Array and ArrayList in Java is one question you may come across in a Java technical interview. Though performance wise both Array and ArrayList may give almost similar performance but functionality wise they both are used in quite different scenarios.

In this post we'll see some of the differences between ArrayList and Array in terms of how they are initialized and the performance they give.

Array Vs ArrayList in Java

  1. First and the most important difference is Array is static and can't be resized once declared.
    Whereas ArrayList is dynamic and that is why also known as dynamic array. ArrayList also uses array of Object internally, but it has the logic to keep growing the size of the array as and when previous size is not able to fit in the number of elements stored in the ArrayList.
  2. Refer: How ArrayList works internally in Java to know more about the internal implementation of ArrayList.

  3. Array can store both primitive types as well as objects whereas ArrayList can store only objects. Though Autoboxing and Unboxing has blurred that difference, but the important point to note here is that in case of ArrayList any primitive data type is still wrapped and stored as an Object.

    For example, if you want an array of primitive type int -

    int[] intArray = new int[3];
    

    Or, if you have a class Employee and you want an array of size 5 to hold 5 Employee objects then -

    Employee[] employees = new Employee[5];
    

    In case of ArrayList if you want to store integers then you have to do this, note the use of wrapper class Integer -

    List<Integer> myList = new ArrayList<Integer>();
    
  4. Difference number 2 between array and ArrayList also indicates one more difference, which is about "type safety". Since Array knows the type of the data which it can hold so it will give compiler error "Type Mismatch" or "ArrayStoreException" if it is not able to resolve it at run time.
    As Exp.
    Object[] names = new String[3];
    names[0] = 12;
    
    This will throw ArrayStoreException.
    Where as this
    String[] names = new String[3];
    names[0] = 12;
    
    Will throw compile time error "Type Mismatch".

    In case of ArrayList, generics brought the much needed type safety which, as shown above, is not required for Array as type of elements stored in the array is specified at the array creation time itself, trying to store element of any other type will result in ArrayStoreException.

    If a list, which should store only Integers, is needed it should be defined as -

    List<Integer> myList = new ArrayList<Integer>();
    

  5. Performance wise both Array and ArrayList are almost similar as ArrayList also uses array of Objects internally and both are index based. But there is some overhead in case of ArrayList in case of resizing the array.
    Since ArrayList stores only objects so memory usage is also more than the array.
  6. Array has length variable which gives the length of the array. Note that length attribute denotes the length of the array at the time of declaration.
    As exp. If an array is declared like this -
    String[] names = new String[3];
    names[0] = "Java";
    
    Then length var will always be 3 even if array names has only one value.

    In case of ArrayList, size() method is used and it will give the size as the current number of elements in the ArrayList.

That's all for this topic Difference Between Array And ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between ArrayList And LinkedList in Java
  2. Difference Between ArrayList And Vector in Java
  3. Difference Between ArrayList And CopyOnWriteArrayList in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. Java Collections Interview Questions

You may also like -

  1. Difference Between Comparable and Comparator in Java
  2. Treemap in Java
  3. Polymorphism in Java
  4. Method overriding in Java
  5. Race condition in Java multi-threading
  6. ThreadLocal class in Java
  7. Lambda expression and exception handling
  8. What is Dependency Injection in Spring