-2

I would like to get an Array of Classes corresponding to the classes of an Array of Objects. I wrote this code:

Object[] parameters = new Object[]{...};

Class[] classes = new Class[parameters.length];
for(int i = 0; i < parameters.length; i++){
  classes[i] = parameters[i].getClass();
}

However, I need primitive types such as int or float writen as float.class or int.class would do, but I instead get java.lang.Float or java.lang.Integrer. Is there anything I could do?

xImperiak
  • 374
  • 1
  • 8
  • Not really, but thanks. I do actually need this for reflection. – xImperiak Mar 07 '21 at 22:54
  • 2
    The values in an `Object[]` can never be primitive types. Only `Float`/`Integer`/... can occur, there's no way you can get a `float`/`int`/ ... here. – Joachim Sauer Mar 07 '21 at 23:00
  • 1
    @Progman: they expect `int.class` to be returned by `parameters[i].getClass()` (where `parameters` is an `Object[]`). That can obviously never happen, as an `Object[]` can not hold primitive values. – Joachim Sauer Mar 07 '21 at 23:02

1 Answers1

3

An Object[] can never contain a primitive type directly. It can only contain the wrapper types Integer/Float/...

This is the reason why classes[i] in your code will never contain int.class.

Note that an Object[] can contain an int[] which in turn can contain int values (and only int values), but that doesn't seem to be what you're looking for.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • And is there any way to get the primitive type form the wrapper type? – xImperiak Mar 07 '21 at 23:14
  • 1
    @xImperiak: unfortunately there's no sweet one-line solution that'll give you that in the JDK, which is why [many utility libraries have such a function](https://stackoverflow.com/questions/1704634/simple-way-to-get-wrapper-class-type-in-java). – Joachim Sauer Mar 08 '21 at 16:36