Reputation: 1925
Let's say I have an object called thisObject
, which may be an int, String, Object, etc., or an array of such classes. I would like the resulting class to be stored in a Class
variable called thisObjectArrayClass
.
This won't compile, but will hopefully explain what I'm looking for:
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;
}
The problem with this is that it relies on a switch/case statement, which is obviously unacceptable. My attempts to do this using reflection failed, but I'm new to Java, so perhaps I did something wrong. How can this be achieved?
Upvotes: 1
Views: 233
Reputation: 3183
You can only switch on integers (or Strings in Java7). Either use an if/else sequence or a switch in 7. Either way the method you are probably looking for is thisObject.getClass()
switch(obj.getClass().getName()) {
case "java.lang.String" :
System.out.println("Found String");
break;
default:
System.out.println("Found:" + obj.getClass().getName());
}
Upvotes: -1
Reputation: 2669
Object has a getClass() method.
public Class getClass(Object thisObject) {
Class thisObjectArrayClass = obj.getClass();
System.out.println("The type of the object is: " + thisObjectArrayClass.getName());
return thisObjectArrayClass;
}
Upvotes: 1
Reputation: 81349
You are looking for Array.newInstance
:
thisObjectArrayClass = Array.newInstance(thisObject.class, 0).getClass();
This instantiates a 0-length array of thisObject.class
es, and requests the class
of such object.
Upvotes: 7