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

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.

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).

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.

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()).

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.

Related

When a class is loaded in java for every .class file separate Class Type object is created why?

In a java program, when a class is loaded into the method area the Class type object is created in the heap area. Questions:
If 10 .class files are loaded then 10 Class type objects are created right?
What is the purpose of creating the Class type object for every .class file by JVM?
There are probably many many reasons. Like: you want to write code such as:
Class<Foo> fooClass = Foo.class;
Annotation[] annotations = fooClass.getAnnotations();
Meaning: the class Class enables you to programmatically inspect (reflect) on your types. Or to use reflection to invoke constructors or methods based on raw strings.
And of course: the JVM itself needs all kinds of information about the classes it knows. So it makes perfect sense to "collect" all that information right at the point when the class is loaded.
Imagine you are a shop owner, and you decide to carry a new item. One of the things to do: update your internal inventory that lists all items, and maybe describes the attributes/properties that matter to you.
After loading a .class file, JVM will create an object of the type java.lang.Class in the Heap area. We can use this class object to get Class level information. It is widely used in Reflection.
Source : https://www.geeksforgeeks.org/object-class-in-java/
I believe this part is handled by JVM's ClassLoader system.
Except the first class of main(), ClassLoader system creates class type objects statically if new is triggered or dynamically if Class.forName() is used. In Object oriented concept class type object is reference to the class.

".class" keyword in Java

I'm currently learning to program on Android using the book Android Programming: The Big Nerd Ranch Guide, and I've encountered this line of code
Intent i = new Intent(getActivity(),CrimeActivity.class);
I can't seem to understand why the Intent's constructor need that second argument.
If my knowledge serves me right, classes in Java are only a blueprint of an object..
So I'm confused why a literal class is passed as an argument in the Intents constructor?
What's happening right there?
In Java, everything except primitive types, is an object. The class definitions we write are wrapped in an Object of Class class. For instance:
class Foo{
}
Foo.class is an instance of Class class.
Class objects hold the information about the class information, like: name, list of instance variables, list of methods etc.
This information can be used at runtime via reflection.
Documentation
According to official developers guide -
This provides a convenient way to create an intent that is intended to
execute a hard-coded class name, rather than relying on the system to
find an appropriate class for you.
You're right, that the class is something like a blueprint for an object. You give the Intent you create that "blueprint" because the Intent itself (resp. the Android system when finally serving your Intent) will create an instance (an object) of the class you passed to it.
That's the reason you pass just the class and not an instance to an Intent.

How does a class literal work? [duplicate]

This question already has answers here:
Closed 10 years ago.
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?
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.
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.
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.
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.
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'

java class initialization explanation

I kind of new to java and will be happy if anybody could explain the following code samples to me.This is just a sample java code snippet for illustration. But the main question is that if the class Learn initializes another class Smart with a parameter which is also a class Object , then the addition of the dot class to the class Object Sample is kind of confusing to me. Any explanation will be appreciated. I apologize if it is a basic question. thanks.
class Learn {
//some codes
Smart smart = new Smart(Sample.class);
//some codes
}
Sample is the name of a class. It is not an object. A new Sample() is an object whose class is Sample. Sample.class is an object whose class is java.lang.Class which describes the class Sample.
In java, there is a class called "Class" that represent classes and interfaces.
There are several ways to get an instance of class "Class". Please take a look at java.lang.Class document.
Class.forName(String className)
obj.getClass() -obj is any class instance
Sample.class -Sample is a class
You are using the 3rd method to get an instance of class "Sample".
I will break your example in the following way....
Learn - is a Class
smart - is an Object Reference Variable of type Smart, we can say that Class Learn has a reference of type Smart.
Sample.class - Is a way of getting the Class<T> for a particular type.
Extract from Java Docs.
During implementation it depends on the Targeting bytecode version. If -target 1.4 (or below), a call to Class.forName() is inserted into your code in a static method which is called during type initialization. If you use -target 1.5 (or above) the constant pool gets a "class" entry
Please refer section 15.8.2 of the Java Language Specification for more details

Class object in Objective C

I am coming from Java to Objective C, and the idea of a class object has me wondering about similarities with Java. From the Objective C guide in Apple documentation:
A class definition's information is compiled and recorded in data structures made available to the runtime systems. The compiler creates just one object, a class object, to represent the class.
So my understanding is that the class object is created for all classes that are going to be used by the program, and a class object is what is used to create objects for that class.
For comparison, does the JVM have a similar object for all classes it loads?
Given that Java was derived directly from Objective-C (no, really, it was), the runtime models of the two are quite similar.
In Java, the notion of a "Class" isn't quite as generic as it is in Objective-C.
In Objective-C, a Class is an instance of what is known as the metaclass. For all intents and purposes, each Class object in Objective-C does exactly as you say; it describes a particular class available in the Objective-C runtime.
The same is conceptually true of Java classes. There is one key difference. In Objective-C, class methods are inherited across subclasses and more significantly a subclass can override a superclass's class method(s).
For example, the NSArray class implements the +array class method (the '+' means "class method"). The NSMutableArray subclass of NSArray overrides +array to return a mutable instance instead.
java.lang.Class is more akin to the Objective-C runtime API; it is the mechanism via which you introspect the classes available in the runtime. Since Java doesn't have functional API, the API is wrapped up in an appropriately named class. java.lang.Class is kinda the runtime API and the metaclass all in one.
A comparable structure in Java would be java.lang.Class.
I think there is a class object for each class.
That class object is the one that, at low level, is used for functions as class_getName(), class_getSuperclass(), class_getVersion(), class_respondsToSelector(). If there would be a single class object for all the classes, then those functions would return the same result for all the classes.

Categories