Eric Conner
Eric Conner

Reputation: 10772

In Java, what does a reference to Class.class do?

I'm building a small Android application, but this is more of a Java question than an android question. Looking through the tutorials there are lines that look like:

startService(new Intent(this, MyService.class));

what exactly does the "MyService.class" field represent? Is that just a reference to the class for a template?

Thanks.

Upvotes: 5

Views: 1003

Answers (4)

samitgaur
samitgaur

Reputation: 5661

In JVM, when a class is loaded, an object of the type Class represents the loaded class in memory. com.abc.MyClass.class is a literal expression that represents the Class object for the class com.abc.MyClass.

The same Class object can also be obtained by calling myClassReference.getClass() method if you have a reference to an object of the class.

The Class object can be used to find the information on the structure of the class, access fields, invoke methods and instantiate objects of the class using Java Reflection API.

Upvotes: 1

The MyService.class allows you to get the Class object describing the MyClass class, from the class name alone (as opposed to have an instance of the class to ask for object.getClass()).

Upvotes: 1

Dan LaRocque
Dan LaRocque

Reputation: 5183

Andy's answer is definitely correct, but I want to expand on the point a little.

.class is a special syntax for obtaining an instance of a Class object. It can be used when only the type is available and no instance of the related object is around. It can be used with any concrete type name, including arrays and primitives. For instance, int.class is valid.

This way (and other ways) to get a Class object are documented in the old Sun reflection API docs.

The special .class syntax often appears in idiomatic usage as a "type token" in generic code. A class literal obtained with .class is called a type token when "passed among methods to communicate both compile-time and runtime type information" (Joshua Bloch's Effective Java 2e, p. 142).

Upvotes: 5

Andy Zhang
Andy Zhang

Reputation: 8315

Yes, MyService.class returns a Class object that represents the class MyService. The Intent uses it to identify which Service or Activity you're intending to start.

Upvotes: 3

Related Questions