Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type of types in Java

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) };
like image 605
marc wellman Avatar asked Dec 09 '13 22:12

marc wellman


People also ask

What are different types in Java?

There are two types of data types in Java: Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

How many types are there in Java?

There are 8 types of Primitive data types in Java – Boolean, char, byte, int, short, long, float, and double.


2 Answers

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
like image 183
Sergey Kalinichenko Avatar answered Oct 01 '22 08:10

Sergey Kalinichenko


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
like image 38
Sage Avatar answered Oct 01 '22 08:10

Sage