1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 package org.apache.hadoop.util;
20 
21 import java.lang.reflect.Array;
22 import java.util.List;
23 
24 import org.apache.hadoop.classification.InterfaceAudience;
25 import org.apache.hadoop.classification.InterfaceStability;
26 
27 /**
28  * Contains utility methods for dealing with Java Generics.
29  */
30 @InterfaceAudience.Private
31 @InterfaceStability.Unstable
32 public class GenericsUtil {
33 
34   /**
35    * Returns the Class object (of type <code>Class&lt;T&gt;</code>) of the
36    * argument of type <code>T</code>.
37    * @param <T> The type of the argument
38    * @param t the object to get it class
39    * @return <code>Class&lt;T&gt;</code>
40    */
getClass(T t)41   public static <T> Class<T> getClass(T t) {
42     @SuppressWarnings("unchecked")
43     Class<T> clazz = (Class<T>)t.getClass();
44     return clazz;
45   }
46 
47   /**
48    * Converts the given <code>List&lt;T&gt;</code> to a an array of
49    * <code>T[]</code>.
50    * @param c the Class object of the items in the list
51    * @param list the list to convert
52    */
toArray(Class<T> c, List<T> list)53   public static <T> T[] toArray(Class<T> c, List<T> list)
54   {
55     @SuppressWarnings("unchecked")
56     T[] ta= (T[])Array.newInstance(c, list.size());
57 
58     for (int i= 0; i<list.size(); i++)
59       ta[i]= list.get(i);
60     return ta;
61   }
62 
63 
64   /**
65    * Converts the given <code>List&lt;T&gt;</code> to a an array of
66    * <code>T[]</code>.
67    * @param list the list to convert
68    * @throws ArrayIndexOutOfBoundsException if the list is empty.
69    * Use {@link #toArray(Class, List)} if the list may be empty.
70    */
toArray(List<T> list)71   public static <T> T[] toArray(List<T> list) {
72     return toArray(getClass(list.get(0)), list);
73   }
74 
75 }
76