1

假设我有一个名为 的对象thisObject,它可能是一个 int、String、Object 等,或者是此类类的数组。我希望将生成的类存储在一个Class名为thisObjectArrayClass.

这不会编译,但希望能解释我在找什么:

switch(thisObject.class) {
    case int.class:
        int[] tempObject;
        thisObjectArrayClass = tempObject.class;
        break;
    case float.class:
        float[] tempObject;
        thisObjectArrayClass = tempObject.class;
        break;
    case int[].class:
        int[][] tempObject;
        thisObjectArrayClass = tempObject.class;
        break;
}

这样做的问题是它依赖于 switch/case 语句,这显然是不可接受的。我尝试使用反射来做到这一点失败了,但我是 Java 新手,所以也许我做错了什么。如何做到这一点?

4

4 回答 4

7

您正在寻找Array.newInstance

thisObjectArrayClass = Array.newInstance(thisObject.class, 0).getClass();

这将实例化一个长度为 0thisObject.class的es数组,并请求class此类对象的 。

于 2012-06-09T05:39:37.587 回答
1

对象有一个 getClass() 方法。

public Class getClass(Object thisObject) {  
    Class thisObjectArrayClass = obj.getClass();  
    System.out.println("The type of the object is: " + thisObjectArrayClass.getName());  
    return thisObjectArrayClass;
} 
于 2012-06-09T05:41:56.953 回答
-1

您只能打开整数(或 Java7 中的字符串)。使用 if/else 序列或 7 中的开关。无论哪种方式,您可能正在寻找的方法是 thisObject.getClass()

switch(obj.getClass().getName()) {
    case "java.lang.String" :
        System.out.println("Found String");
        break;
    default:
        System.out.println("Found:" + obj.getClass().getName());
}
于 2012-06-09T05:48:00.377 回答
-2
int array[] = new int[7];
array.getClass();
于 2012-06-10T01:31:23.060 回答