de.lmu.ifi.dbs.elki.utilities
Class ClassGenericsUtil

java.lang.Object
  extended by de.lmu.ifi.dbs.elki.utilities.ClassGenericsUtil

public final class ClassGenericsUtil
extends Object

Utils for handling class instantiation especially with respect to Java generics.

Due to the way generics are implemented - via erasure - type safety cannot be guaranteed properly at compile time here. These classes collect such cases using helper functions, so that we have to suppress these warnings only in one place.

Note that many of these situations are still type safe, i.e. an empty array of List> can indeed be cast into a List>.

The only one potentially unsafe is instantiateGenerics(java.lang.Class, java.lang.String), since we can't verify that the runtime type 'type' adhers to the compile time restriction T. When T is not generic, such a check is possible, and then the developer should use instantiate(java.lang.Class, java.lang.String) instead.


Field Summary
static String FACTORY_METHOD_NAME
          Name for a static "parameterize" factory method.
private static Logging logger
          Static logger to use.
 
Constructor Summary
ClassGenericsUtil()
           
 
Method Summary
static
<B,T extends B>
T
castWithGenericsOrNull(Class<B> base, Object obj)
          Cast an object at a base class, but return a subclass (for Generics!).
static
<T,C extends Collection<T>>
C
cloneCollection(C coll)
          Clone a collection.
static
<T> T[]
collectionToArray(Collection<T> c, T[] a)
          Transform a collection to an Array
static
<T> Class<? extends T>
getComponentType(T[] a)
          Retrieve the component type of a given array.
static
<C> Method
getParameterizationFactoryMethod(Class<C> c, Class<?> ret)
          Inspect the class for a static "parameterize" method that satisfies certain constraints.
static Parameterizer getParameterizer(Class<?> c)
          Get a parameterizer for the given class.
static
<T> T
instantiate(Class<T> type, String className)
           Returns a new instance of the given type for the specified className.
static
<T> T
instantiateGenerics(Class<?> type, String className)
           Returns a new instance of the given type for the specified className.
static
<T> T[]
newArray(Class<? extends T> k, int size)
          Make a new array of the given class and size.
static
<T> T[]
newArray(T[] a, int size)
          Clone an array of the given type.
static
<T> ArrayList<T>[]
newArrayOfEmptyArrayList(int len)
          Create an array of len empty ArrayLists.
static
<T> HashSet<T>[]
newArrayOfEmptyHashSet(int len)
          Create an array of len empty HashSets.
static
<T> T[]
newArrayOfNull(int len, Class<T> base)
          Create an array (of null values) This is a common unchecked cast we have to do due to Java Generics limitations.
static
<T> T
newInstance(T obj)
          Generic newInstance that tries to clone an object.
static
<C> C
parameterizeOrAbort(Class<?> c, Parameterization config)
          Force parameterization method.
static
<B,T extends B>
T[]
toArray(Collection<T> coll, Class<B> base)
          Convert a collection to an array.
static
<C> C
tryInstantiate(Class<C> r, Class<?> c, Parameterization config)
          Instantiate a parameterizable class.
static
<D,T extends D>
Class<T>
uglyCastIntoSubclass(Class<D> cls)
          Cast the (erased) generics onto a class.
static
<BASE,FROM extends BASE,TO extends BASE>
Class<TO>
uglyCrossCast(Class<FROM> cls, Class<BASE> base)
          This class performs an ugly cast, from Class<F> to Class<T>, where both F and T need to extend B.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

private static final Logging logger
Static logger to use.


FACTORY_METHOD_NAME

public static final String FACTORY_METHOD_NAME
Name for a static "parameterize" factory method.

See Also:
Constant Field Values
Constructor Detail

ClassGenericsUtil

public ClassGenericsUtil()
Method Detail

instantiate

public static <T> T instantiate(Class<T> type,
                                String className)
                     throws UnableToComplyException

Returns a new instance of the given type for the specified className.

If the Class for className is not found, the instantiation is tried using the package of the given type as package of the given className.

Type Parameters:
T - Class type for compile time type checking
Parameters:
type - desired Class type of the Object to retrieve
className - name of the class to instantiate
Returns:
a new instance of the given type for the specified className
Throws:
UnableToComplyException - if the instantiation cannot be performed successfully

instantiateGenerics

public static <T> T instantiateGenerics(Class<?> type,
                                        String className)
                             throws UnableToComplyException

Returns a new instance of the given type for the specified className.

If the Class for className is not found, the instantiation is tried using the package of the given type as package of the given className.

This is a weaker type checked version of "instantiate(java.lang.Class, java.lang.String)" for use with Generics.

Type Parameters:
T - Class type for compile time type checking
Parameters:
type - desired Class type of the Object to retrieve
className - name of the class to instantiate
Returns:
a new instance of the given type for the specified className
Throws:
UnableToComplyException - if the instantiation cannot be performed successfully

getParameterizationFactoryMethod

public static <C> Method getParameterizationFactoryMethod(Class<C> c,
                                                          Class<?> ret)
                                               throws NoSuchMethodException,
                                                      Exception
Inspect the class for a static "parameterize" method that satisfies certain constraints.

Type Parameters:
C - Return class type
Parameters:
c - Class to inspect.
ret - Expected return type
Returns:
factory method that can be called with factory(null, Parameterization).
Throws:
NoSuchMethodException - When no factory method was found, or it doesn't fit the constraints.
Exception - On other errors such as security exceptions

getParameterizer

public static Parameterizer getParameterizer(Class<?> c)
Get a parameterizer for the given class.

Parameters:
c - Class
Returns:
Parameterizer or null.

tryInstantiate

public static <C> C tryInstantiate(Class<C> r,
                                   Class<?> c,
                                   Parameterization config)
                        throws InvocationTargetException,
                               NoSuchMethodException,
                               Exception
Instantiate a parameterizable class. When using this, consider using Parameterization.descend(java.lang.Object)!

Type Parameters:
C - base type
Parameters:
r - Base (restriction) class
c - Class to instantiate
config - Configuration to use for instantiation.
Returns:
Instance
Throws:
InvocationTargetException - when an exception occurred within the constructor
NoSuchMethodException - when no suitable constructor was found
Exception - when other instantiation errors occurred

parameterizeOrAbort

public static <C> C parameterizeOrAbort(Class<?> c,
                                        Parameterization config)
Force parameterization method. Please use this only in "runner" classes such as unit tests, since the error handling is not very flexible.

Type Parameters:
C - Type
Parameters:
c - Class to instantiate
config - Parameters
Returns:
Instance or throw an AbortException

newArrayOfNull

public static <T> T[] newArrayOfNull(int len,
                                     Class<T> base)
Create an array (of null values) This is a common unchecked cast we have to do due to Java Generics limitations.

Type Parameters:
T - Type the array elements have
Parameters:
len - array size
base - template class for array creation.
Returns:
new array of null pointers.

toArray

public static <B,T extends B> T[] toArray(Collection<T> coll,
                                          Class<B> base)
Convert a collection to an array.

Type Parameters:
B - Base type
T - Type the array elements have
Parameters:
coll - collection to convert.
base - Template class for array creation.
Returns:
new array with the collection contents.

newArrayOfEmptyArrayList

public static <T> ArrayList<T>[] newArrayOfEmptyArrayList(int len)
Create an array of len empty ArrayLists. This is a common unchecked cast we have to do due to Java Generics limitations.

Type Parameters:
T - Type the list elements have
Parameters:
len - array size
Returns:
new array of ArrayLists

newArrayOfEmptyHashSet

public static <T> HashSet<T>[] newArrayOfEmptyHashSet(int len)
Create an array of len empty HashSets. This is a common unchecked cast we have to do due to Java Generics limitations.

Type Parameters:
T - Type the set elements have
Parameters:
len - array size
Returns:
new array of HashSets

uglyCastIntoSubclass

public static <D,T extends D> Class<T> uglyCastIntoSubclass(Class<D> cls)
Cast the (erased) generics onto a class. Note: this function is a hack - notice that it would allow you to up-cast any class! Still it is preferable to have this cast in one place than in dozens without any explanation. The reason this is needed is the following: There is no Class<Set<String>>.class. This method allows you to do Class<Set<String>> setclass = uglyCastIntoSubclass(Set.class); We can't type check at runtime, since we don't have T.

Type Parameters:
D - Base type
T - Supertype
Parameters:
cls - Class type
Returns:
cls parameter, but cast to Class<T>

uglyCrossCast

public static <BASE,FROM extends BASE,TO extends BASE> Class<TO> uglyCrossCast(Class<FROM> cls,
                                                                               Class<BASE> base)
This class performs an ugly cast, from Class<F> to Class<T>, where both F and T need to extend B. The restrictions are there to avoid misuse of this cast helper. While this sounds really ugly, the common use case will be something like
 BASE = Class<Database>
 FROM = Class<Database>
 TO = Class<Database<V>>
 
i.e. the main goal is to add missing Generics to the compile time type.

Type Parameters:
BASE - Base type
TO - Destination type
FROM - Source type
Parameters:
cls - Class to be cast
base - Base class for type checking.
Returns:
Casted class.

castWithGenericsOrNull

public static <B,T extends B> T castWithGenericsOrNull(Class<B> base,
                                                       Object obj)
Cast an object at a base class, but return a subclass (for Generics!). The main goal of this is to allow casting an object from e.g. " List" to "List<Something>" without having to add SuppressWarnings everywhere.

Type Parameters:
B - Base type to cast at
T - Derived type returned
Parameters:
base - Base class to cast at
obj - Object
Returns:
Cast object or null.

newInstance

public static <T> T newInstance(T obj)
                     throws InstantiationException,
                            IllegalAccessException,
                            InvocationTargetException,
                            NoSuchMethodException
Generic newInstance that tries to clone an object.

Type Parameters:
T - Object type, generic
Parameters:
obj - Master copy - must not be null.
Returns:
New instance, if possible
Throws:
InstantiationException - on error
IllegalAccessException - on error
InvocationTargetException - on error
NoSuchMethodException - on error

getComponentType

public static <T> Class<? extends T> getComponentType(T[] a)
Retrieve the component type of a given array. For cloning.

Type Parameters:
T - Array type, generic
Parameters:
a - Existing array
Returns:
Component type of the given array.

newArray

public static <T> T[] newArray(Class<? extends T> k,
                               int size)
Make a new array of the given class and size.

Type Parameters:
T - Generic type
Parameters:
k - Class
size - Size
Returns:
new array of the given type

newArray

public static <T> T[] newArray(T[] a,
                               int size)
Clone an array of the given type.

Type Parameters:
T - Generic type
Parameters:
a - existing array
size - array size
Returns:
new array

cloneCollection

public static <T,C extends Collection<T>> C cloneCollection(C coll)
Clone a collection. Collection must have an empty constructor!

Type Parameters:
T - Data type
C - Collection type
Parameters:
coll - Existing collection
Returns:
Cloned collection

collectionToArray

public static <T> T[] collectionToArray(Collection<T> c,
                                        T[] a)
Transform a collection to an Array

Type Parameters:
T - object type
Parameters:
c - Collection
a - Array to write to or replace (i.e. sample array)
Returns:
new array containing the collection elements

Release 0.4.0 (2011-09-20_1324)