careLess
careLess

Reputation: 83

What does it mean by "the type of the class modeled by this Class object"?

From the Java Documentation:

T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.

What exact does "the type of the class modeled by this Class object" mean? Pardon, but this something look odd to me and I can't understand that much.

Upvotes: 4

Views: 118

Answers (2)

Sweeper
Sweeper

Reputation: 270995

As you may know, classes represent (in other words, model) things. A String represents a bunch of characters, a FileInputStream represents a file input stream, a LocalDateTime represents a date and time without a timezone, etc.

If you can understand that, then you should be able to understand that there is a class that represents the concept of "classes", called Class. This class is generic. Its single generic parameter is the class that it represents. For example, Class<String>, represents the class String, Class<LocalDateTime> represents the class LocalDateTime. This is what the documentation meant.

Let's see a concrete example:

Class<String> clazz = String.class;
System.out.println(clazz.getName());

In the first line I have retrieved an instance of Class<String> (or a Class<String> object). Now the object inside the variable clazz represents the String class! How cool is that? We can print the name of the String class by calling getName on clazz, as you can see on the second line. You can do other cool things with clazz as well, such as seeing what interfaces it implements, what is its superclass, what method it has, etc. This is what I mean by "the Class<String> object represents the String class.

Upvotes: 3

Kirill
Kirill

Reputation: 8311

T type parameter is generic parameter, see https://docs.oracle.com/javase/tutorial/java/generics/. In case of Class<T> it's type of instance of the class. As you can see from javadoc this parameter is used in several methods: T newInstance(), T cast(), Constructor<T> constructor(). E.g. you may instantiate new instance of T type from Class<T> object:

Class<String> cls = String.class;
String str = cls.newInstance();

or cast to this class:

Object obj = "some string";
Class<String> cls = String.class;
String str = cls.cast(obj);

Upvotes: 1

Related Questions