Question

At the risk of asking a question that has already been asked but

is there a counterpart in Java for the Type type available in C# ?

What I want to do is filling an array with elements which reflect several primitive types such as int, byte etc.

In C# it would be the following code:

Type[] types = new Type[] { typeof(int), typeof(byte), typeof(short) };
Était-ce utile?

La solution

Yes, these are available through their wrapper's TYPE fields:

Class[] types = new Class[] {Integer.TYPE, Byte.TYPE, ...};

You can also use int.class syntax, which has not been available in earlier versions of the language:

Class[] types = new Class[] {int.class, byte.class, ...}; // Lowercase is important

Autres conseils

Are you talking about:

Class[] aClass = {Integer.class, Short.class, Byte.class};

However, to emphasize the difference with Integer.TYPE and Integer.class: Integer.TYPE is in fact a Class<Integer> type and: Integer.TYPE is equivalent to int.class

System.out.println(Integer.class == Integer.TYPE); // false
System.out.println(Integer.TYPE == int.class); // true
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top