1

Possible Duplicate:
What is a class literal in Java?

I was going through literals in the Java tutorial where I came across this sentence:

Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.

Which doesn't make any sense to me, even though I paid attention to all the other topics prior to this. Can anyone explain in simple language with examples or references?

Community
  • 1
  • 1

5 Answers5

4

Instances of the class java.lang.Class represent classes and interfaces in a running Java application. For each class in the application, there is an instance of Class. The SomeClass.class syntax is a way to get from SomeClass to the corresponding instance of Class.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Would it be worth adding "without instantiating a new `SomeClass`" or is that obvious? I know that `.class` is really usful with things like dependency injection and ORMs where the characteristics of a class are not known at compile time – Jason Sperske Jan 10 '13 at 18:26
2

A class literal is just a special type to use when you want to do something involving the class itself, rather than an instance.

Here's a short list of a few things I commonly use this for (not at all comprehensive, but you can get a good idea)

1.) Reflection, you want to instantiate something in run-time that you may not know (perhaps it was stored in a variable of type Class)

2.) You want to check if 2 objects are of the same related type, you can write something along the lines of: B.class.isAssignableFrom(a.getClass());

3.) You want to list all the methods, or public variables within a class, perhaps for documentation.

There are many other uses, but these are the main ones I find myself using in common practice.

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
1

Speaking simple language: that thing, which you call class literal is an object which fully describes some class: all its methods, all its fields, all its annotations, class's modifiers and so on. It is needed for creating new instances of that class in runtime.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
0

Short example:

    Class x = String.class;
    System.out.println(x);

you can use x to create runtime instances of the class it points to or to test the class of an object against it.

sqreept
  • 5,236
  • 3
  • 21
  • 26
0

It evaluates to be the class identifier of the reference or primitive type's wrapper class. The expression void.class evaluates to the class identifier of the Void class. Same thing with 'String.class'

zizou.
  • 1
  • 2