shuba gopal wrote:I understand that String.class,Boolean.class,Integer.class etc are class literals. Are these objects by themselves?
Yes. They are [references to] instances of the class Class.
shuba gopal wrote:Object o = Long.class compiles but can someone tell me exactly why we use these fields?
No, I don't really understand the question. I can't conceive of any realistic scenario where you'd want to assign Long.class to an Object variable named "o". There may well be a good reason, but I don't know it offhand. The compiler will let you do all sorts of random useless crap if you want to. It's up to you to decide if a thing is worth doing or not, and to know your reasons.
shuba gopal wrote:Math.sqrt - is this a valid example of class literals?
No. It's valid code, but there are no class literals there.
shuba gopal wrote:(For static methods instead of creating objects we can use the class name as reference.
Not really a "reference"; that's something else, like a variable that contains a reference to an object. This isn't a reference, because a reference would refer to an object, and this doesn't. This is part of a fully qualified name.
shuba gopal wrote:For static nested classes we use the nested class' name as a reference instead of creating an instance. Is this also a use of class literals?
No, there are no class literals involved here.
Joined: May 12, 2011
Mike thanks, Object o = Long.class really confused me. Thanks for explaining
Shuba - the key thing to understand is that "class" is a Java keyword. The ".class" in "Foo.class" is not a field; it's more akin the the quote marks in a String literal: just a way of representing an actual object.
Math.sqrt doesn't mean anything on its own. If you follow it with parentheses and a number, you are calling a static method. Static methods are methods that are defined in a class but don't operate on an instance of the class, and so you call them using the class name rather than an instance name.
Joined: May 12, 2011
Luigi thanks. That was a very good explanation. Can you tell me what is the use for the declaration Obj o = Long.class. In general what is the use of class literals?
As Mike said, it's hard to conceive of a use for that particular declaration. It looks completely useless.
In general I don't think you'll need to use class literals very much, unless you're doing something quite advanced, like reflection, or loading up classes. The only time I've ever used it was when building a GUI to launch Runnable classes, and I needed to load a bunch of classes from a folder and check that they implemented the Runnable interface. It contained the line where "target" was the name of a Class object being checked.