May 15

Short answer is you can’t.

Generics use type erasure which means the compiler removes all information related to the parameters within the class. This is done to maintain binary compatibility with classes that were created before generics.

public class MyClass<T> {
    public void myMethod(Object item) {
        if (item instanceof T) {     // Compiler error
            // do something
        }
        Class<T> c1 = T.class;       // Compiler error
        Class<T> c2 = T.getClass();  // Compiler error
        T item2 = new T();           // Compiler error
        T[] array = new T[10];       // Compiler error
        T o = (T) new Object();      // Unchecked cast warning
    }
}

written by objects \\ tags: ,

Oct 13

The following utility method will allow you to merge any number of arrays.


    public static <T> T[] arrayMerge(T[]... arrays)
    {
        // Determine required size of new array

        int count = 0;
        for (T[] array : arrays)
        {
            count += array.length;
        }

        // create new array of required class

        T[] mergedArray = (T[]) Array.newInstance(
           arrays[0][0].getClass(),count);

        // Merge each array into new array

        int start = 0;
        for (T[] array : arrays)
        {
            System.arraycopy(array, 0, 
               mergedArray, start, array.length);
            start += array.length;
        }
        return (T[]) mergedArray;
    } 

written by objects \\ tags: , ,

Sep 25

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyBean implements Comparable<MyBean>
{
   private int value;

   public MyBean()
   {
   }

   public MyBean(int value)
   {
      setValue(value);
   }

   public int getValue()
   {
      return value;
   }

   public void setValue(int value)
   {
      this.value = value;
   }

   public int compareTo(MyBean other)
   {
       return value - other.value;
   }

   public String toString()
   {
	   return Integer.toString(value);
   }
   
   public static void main(String[] args)
   {
      List<MyBean> listOfMyBeans = new ArrayList<MyBean>();
      listOfMyBeans.add(new MyBean(5));
      listOfMyBeans.add(new MyBean(1));
      listOfMyBeans.add(new MyBean(4));

      Collections.<MyBean>sort(listOfMyBeans);

      System.out.println(listOfMyBeans);
   }
} 

written by objects \\ tags: , , , ,