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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17607974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:27:27  来源:igfitidea点击:

Determining the type of objects in a collection or array

javaarrayscollections

提问by Rishi

Suppose I have an array int[][] or an array char[][] or an ArrayList. Is there a way in java to know the base class type of the array. For Example:

假设我有一个数组 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)

Can this be done in Java?

这可以用Java完成吗?

回答by tom

Arrays(e.g. int[][])

数组(例如int[][]

You can get the array's component type using getComponentType():

您可以使用getComponentType()获取数组的组件类型:

(new int[10][10]).getClass().getComponentType().getComponentType(); // int

For arrays of arbitrary depth use a loop:

对于任意深度的数组,使用循环:

Object array = new int[10][][][];
Class<?> type = array.getClass();
while (type.isArray())
{
    type = type.getComponentType();
}
assert type == Integer.TYPE;

Generic Types(e.g. ArrayList<Integer>)

通用类型(例如ArrayList<Integer>

It is not possible to get the type parameter. Java uses type erasure, so the information is lost at runtime.

无法获取类型参数。Java 使用类型擦除,因此信息在运行时丢失。

You can guess the declared type of collections based on the types of the elements:

您可以根据元素的类型猜测集合的声明类型:

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
    }
}

回答by Chase

You could use the classes getComponentType(). For example.

你可以使用类getComponentType()。例如。

public static final Class<?> getBaseType(Object obj) {
    Class<?> type = obj.getClass();
    while (type.isArray()) {
        type = type.getComponentType();
    }
    return type;
}

typewill then be whatever the base type is.

type然后将是任何基本类型。

This will work if objis double[][][][][][]or just double[], or something else.

如果objisdouble[][][][][][]或 justdouble[]或其他东西,这将起作用。

As for generics, those things in <and >. Type erasure occurs, meaning you cannot determine what type those are from the ArrayListitself.

至于泛型,<>. 发生类型擦除,这意味着您无法确定它们ArrayList本身是什么类型。

回答by Darshan Mehta

In case of arrays, it can be identified via the type of an array, (e.g. arrayof int[][]will always give you int.

在数组的情况下,它可以通过 an 的类型来识别array(例如arrayofint[][]总是会给你int.

In case of ArrayList, if your ArrayListis heterogeneous objects then, get(i)will always give you the element of type Object. To know its class, you can use getClass()method of Object.

在 的情况下ArrayList,如果您ArrayList是异构对象,那么get(i)将始终为您提供 type 元素Object。要知道它的类,你可以使用getClass()的方法Object

回答by emphywork

Following code works...as you asked..

以下代码有效......正如你所问的......

Here, I have used

在这里,我用过

object.getClass().getSimpleName()

object.getClass().getSimpleName()

for arraylist you must add an item of specific type since you are using generics. and then get them and have it use same getClass().getSimpleName() method.

对于 arraylist,您必须添加特定类型的项目,因为您使用的是泛型。然后获取它们并使用相同的 getClass().getSimpleName() 方法。

  public class ShowObjectType {
        public static void main(String[] args) {
            int arr[][] = { { 2, 3 }, { 4, 0 } };
            char[][] arr1 = { { 'a', 'c' }, { 'b', 'd' } };
            ArrayList<Integer> arr2 = new ArrayList<Integer>();
            arr2.add(4);
            ArrayList<Point> arr3 = new ArrayList<Point>();
            arr3.add(new Point());
            System.out.println(arr.getClass().getSimpleName());
            System.out.println(arr1.getClass().getSimpleName());
                System.out.println(arr2.get(0).getClass().getSimpleName());
            System.out.println(arr3.get(0).getClass().getSimpleName());
        }
    }

    class Point {

    }

hope it helps

希望能帮助到你

回答by Manish Doshi

Two ways to do this:

有两种方法可以做到这一点:

  1. Use the instanceofoperator.

  2. Call getClass()on the object (make sure to check for null first).

  1. 使用instanceof运算符。

  2. 调用getClass()对象(确保首先检查 null)。

For this you can also refer which i found: http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html

为此,您还可以参考我发现的内容:http: //docs.oracle.com/javase/tutorial/reflect/class/classNew.html

回答by Joshua Wilson

Yes, those are called Generics. But is better to think that it forces the Arraylist to only hold "point" objects.

是的,那些被称为泛型。但最好认为它强制 Arraylist 只保存“点”对象。

回答by Alexey Odintsov

For primitive types you can use this code:

对于原始类型,您可以使用以下代码:

public static void main(String[] args) {
    int arr[] = {1,2,3};
    int arr2[][] = {{1},{2},{3}};
    char arrc[] = {'v', 'c', 'r'};

    System.out.println(arr.getClass().getCanonicalName());      
    System.out.println(arr2.getClass().getCanonicalName());     
    System.out.println(arrc.getClass().getCanonicalName());
}

the output is:

输出是:

int[]
int[][]
char[]

For ArrayList if you need to work with its elements (if list is not empty) you may check the type of the first element

对于 ArrayList,如果您需要处理其元素(如果列表不为空),您可以检查第一个元素的类型

    ArrayList<Integer> arrInt = new ArrayList<Integer>();
    arrInt.add(100);

    if (arrInt instanceof List && arrInt.size() > 0) {
        System.out.println(arrInt.get(0).getClass().getCanonicalName());
    }   

回答by Parkash Kumar

You can get base type of Array as:

您可以获得 Array 的基本类型为:

Object obj = new Long[0];
Class ofArray = obj.getClass().getComponentType();

For Collection type, you can use the getClass() method, or you can use instanceof. For example:

对于 Collection 类型,可以使用 getClass() 方法,也可以使用 instanceof。例如:

ArrayList<Object> list = ...;

for (Object obj : list) {
   if (obj instanceof String) {
   ...
   }
}


for (Object o : list) {
    if (o.getClass().equals(Integer.TYPE)) {
        handleInt((int)o);
    }
    else if (o.getClass().equals(String.class)) {
        handleString((String)o);
    }
    ...
}