• Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested .class reference  RSS feed

 
Sudar Shan
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am looking at the following mapreduce example and don't understand what does the word count.class signify in the main method. What is the .class for?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You can find some details of this is the Java tutorials...

https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html


Henry
 
Sudar Shan
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Henry for the response and also for fixing my code tag.

Does that mean that .getName() and .class give the same result (except for primitive type where .getName doesn't work)?
 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sudar Shan wrote:. . .
Does that mean that .getName() and .class give the same result (except for primitive type where .getName doesn't work)?
No. Not at all.
The .getName method is a method of the Class class which returns a String representing its name.
The .class construct, which I think is called a class literal allows you to get the Class<?> object by passing the name of the class.
 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It appears from the JLS link that you can use .class after the name of a primitive. Using .class is a bit like a static version of .getClass().
 
Sudar Shan
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I have now understood a bit; .getName() works on an instance of a Class and .class works on the Class name itself. So, I am assuming that ".class" is similar to a static method.

Since the example I had posted is not actually instantiating the class but only wants to get the class name, .class has been used. (right?)

 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sudar Shan wrote:. . . ".class" is similar to a static method.
. . .
Not quite a static method and not quite a static field. It is a special way to load a Class<?> object without having an instance to use getClass() on. If you print out a Class<?> object, you can find out what you see here. And while you are going through the Class class, have a look at this method.

I see in the earlier JLS link, if you try int.class you are going to get the Class<Integer> object. Don't know what happened before boxing was introduced.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!