java - 确定集合或数组中对象的类型

标签 java arrays collections

假设我有一个数组 int[][] 或一个数组 char[][] 或一个 ArrayList。 java中有没有办法知道数组的基类类型。例如:

int[][] gives output as int.
char[][] gives output as char.
ArrayList<Integer> gives output Integer.
ArrayList<Point> gives Point. (It should also work for a custom type)

这可以用 Java 完成吗?

最佳答案

数组(例如 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
    }
}

关于java - 确定集合或数组中对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607974/

相关文章:

java - 停止所有 Awt/Swing 线程和监视器以及其他东西,以便只剩下主线程

php - 对 PHP 数组编号进行分组

javascript - 带有对象的数组上的 .forEach 将不会运行

java - 如何根据索引而不是键从 LinkedHashMap 获取值?

java - 如何在不调用规则的情况下测试 drool 文件中存在的函数?

java - 多核环境中原子操作的线程安全

ios - 空数组错误 - 无法将数据从现有的 NSMutableArray 传递到 NSString

java - ArrayList 排序无法正常工作

java - 是否有用于 Java 自定义集合实现的测试套件?

java - Hashmap 哈希表大小限制小于数组索引允许的最大限制