| Author |
ClassName.class
|
Malatesh Karabisti
Ranch Hand
Joined: Jul 28, 2010
Posts: 143
|
|
Can please any body explain
1)public class ThredsLetters extends Thread {
public static void main(String[] args) {
System.out.println(ThredsLetters.class);
}
}
what is the class the above statement ?
2)synchronized(Letters.class) is it valid ? if yes what we are synchronizing here ?
|
 |
Valentin Musoiu
Greenhorn
Joined: Jul 21, 2010
Posts: 21
|
|
Wait—what's that MyClass.class thing? That's called a class literal. It's a
special feature in the Java language that tells the compiler (who tells the JVM): go
and find me the instance of Class that represents the class called MyClass.
KS&BB page 738
So... class literal...
Now I think you can guess the answer to the second question, too (Hint: it should be in a static method!)
Hope this helps!
|
OCPJP 6 95%
|
 |
Malatesh Karabisti
Ranch Hand
Joined: Jul 28, 2010
Posts: 143
|
|
|
Valentin, can you please elaborate ?
|
 |
Valentin Musoiu
Greenhorn
Joined: Jul 21, 2010
Posts: 21
|
|
Hey, Malatesh!
Sorry for being too succint!
ThredsLetters.class is a class literal... Just like 5 is an int literal, like 5.0 is a double literal (surprisingly, there is a class named 'Class' in java.lang package).
Therefore you can print the class literal (just like you can print any object... you get what the toString() method returns in the Class class). You can have a Class variable. In fact, I imagine you can do all sorts of things, but I haven't got the time to experiment, as it is not asked for SCJP
On the second matter, synchronized(Letters.class) is used when you synchronize a static block of code. You probably know that you can synchronize methods and blocks either static or non-static:
- when you synchronize a non-static method, you simply use "synchronize" keyword to synchronize on the current object
- when you synchronize a non-static block, you have to say what object are you synchronizing on [ ex: synchronize(this) ]
Similarly:
- when you synchronize a static method, you simply use "synchronize" keyword to synchronize on the current class
- when you synchronize a static block, you have to say what class are you synchronizing on [ ex: synchronize(MyClass.class) ]
Hope this time I explained it better!
PS: If I said something stupid (hope I didn't, but.. who knows?), please someone correct me!
PPS: I claim the prize for the most 'synchronize' words in a single post :p
|
 |
Malatesh Karabisti
Ranch Hand
Joined: Jul 28, 2010
Posts: 143
|
|
Valentin , I think you spent good amount of efforts to explain it from bottom, for that you deserve round of applause , It is more clear now, we mostly used only two words “class” and as you said “synchronize” 200 times in a discussion of 1000 words
Thanks for your efforts.
|
 |
 |
|
|
subject: ClassName.class
|
|
|