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 | /** |
---|
25 | * Contains utility methods for dealing with Java Generics. |
---|
26 | */ |
---|
27 | public class GenericsUtil { |
---|
28 | |
---|
29 | /** |
---|
30 | * Returns the Class object (of type <code>Class<T></code>) of the |
---|
31 | * argument of type <code>T</code>. |
---|
32 | * @param <T> The type of the argument |
---|
33 | * @param t the object to get it class |
---|
34 | * @return <code>Class<T></code> |
---|
35 | */ |
---|
36 | public static <T> Class<T> getClass(T t) { |
---|
37 | @SuppressWarnings("unchecked") |
---|
38 | Class<T> clazz = (Class<T>)t.getClass(); |
---|
39 | return clazz; |
---|
40 | } |
---|
41 | |
---|
42 | /** |
---|
43 | * Converts the given <code>List<T></code> to a an array of |
---|
44 | * <code>T[]</code>. |
---|
45 | * @param c the Class object of the items in the list |
---|
46 | * @param list the list to convert |
---|
47 | */ |
---|
48 | public static <T> T[] toArray(Class<T> c, List<T> list) |
---|
49 | { |
---|
50 | @SuppressWarnings("unchecked") |
---|
51 | T[] ta= (T[])Array.newInstance(c, list.size()); |
---|
52 | |
---|
53 | for (int i= 0; i<list.size(); i++) |
---|
54 | ta[i]= list.get(i); |
---|
55 | return ta; |
---|
56 | } |
---|
57 | |
---|
58 | |
---|
59 | /** |
---|
60 | * Converts the given <code>List<T></code> to a an array of |
---|
61 | * <code>T[]</code>. |
---|
62 | * @param list the list to convert |
---|
63 | * @throws ArrayIndexOutOfBoundsException if the list is empty. |
---|
64 | * Use {@link #toArray(Class, List)} if the list may be empty. |
---|
65 | */ |
---|
66 | public static <T> T[] toArray(List<T> list) { |
---|
67 | return toArray(getClass(list.get(0)), list); |
---|
68 | } |
---|
69 | |
---|
70 | } |
---|