阵列(如int[][]
)
可以使用数组的组件类型getComponentType()得到:
(new int[10][10]).getClass().getComponentType().getComponentType(); // int
对于任意深度的数组,使用循环:
Object array = new int[10][][][];
Class<?> type = array.getClass();
while (type.isArray())
{
type = type.getComponentType();
}
assert type == Integer.TYPE;
通用类型(例如, ArrayList<Integer>
)
无法获取类型参数。 Java使用type erasure,所以信息在运行时会丢失。
可以猜测基础上的类型元素的集合声明的类型:
import java.util.*;
public class CollectionTypeGuesser
{
static Set<Class<?>> supers(Class<?> c)
{
if (c == null) return new HashSet<Class<?>>();
Set<Class<?>> s = supers(c.getSuperclass());
s.add(c);
return s;
}
static Class<?> lowestCommonSuper(Class<?> a, Class<?> b)
{
Set<Class<?>> aSupers = supers(a);
while (!aSupers.contains(b))
{
b = b.getSuperclass();
}
return b;
}
static Class<?> guessElementType(Collection<?> collection)
{
Class<?> guess = null;
for (Object o : collection)
{
if (o != null)
{
if (guess == null)
{
guess = o.getClass();
}
else if (guess != o.getClass())
{
guess = lowestCommonSuper(guess, o.getClass());
}
}
}
return guess;
}
static class C1 { }
static class C2 extends C1 { }
static class C3A extends C2 { }
static class C3B extends C2 { }
public static void main(String[] args)
{
ArrayList<Integer> listOfInt = new ArrayList<Integer>();
System.out.println(guessElementType(listOfInt)); // null
listOfInt.add(42);
System.out.println(guessElementType(listOfInt)); // Integer
ArrayList<C1> listOfC1 = new ArrayList<C1>();
listOfC1.add(new C3A());
System.out.println(guessElementType(listOfC1)); // C3A
listOfC1.add(new C3B());
System.out.println(guessElementType(listOfC1)); // C2
listOfC1.add(new C1());
System.out.println(guessElementType(listOfC1)); // C1
}
}
来源
2013-07-12 05:37:48
tom
ArrayList的''是错误的,必须是ArrayList的''不要 –
ajduke
不知道他是怎么说“编译” – mattbdean
这不是一个代码,因此它不会编译。 – Rishi