Java – What is the correct meaning of SecondActivity .class in Android Intent?

What is the correct meaning of SecondActivity .class in Android Intent?… here is a solution to the problem.

What is the correct meaning of SecondActivity .class in Android Intent?

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startService(intent);

My understanding is that until this line of code “SecondActivity object” is not created and we are sending the runtime data of the SecondActivity to Intent. So, I think at runtime the compiler will add some extra code to the second activity.

I

know it’s related to reflections, but I still don’t understand it correctly. Whether “.class” represents a “static variable class” of type “Class” in the run-time “SecondActivity” class, for example

static Class class = .......

Do we access class objects through “class static variables”? Did the compiler add this static variable at runtime, and we got the “class object” of SecondActivity through it? Am I understanding correctly?

Solution

If I understand your question, it is “What is SecondActivity.class? and/or “What is .class?” ”

While this is not necessarily an Android issue, I understand the context and acknowledge that it can be interpreted that way.

Essentially, “.class” means that a class (in your example) is an implementation of an Android service, so calling startService(intent) will create an Object instance from that class and set it as a service.

The actual SecondActivity.class can be thought of as a constant reference to the class “SecondActivity“. This is all managed by the Java Virtual Machine (JVM).

This means that calling SecondActivity .class as a static variable is almost correct, except that it is more of a static constant because it always refers to a class called SecondActivity, which is either loaded into memory or will be loaded into memory.

Advanced explanation:

The class reference calls the current classloader to get or load the referenced class. If the class is not already loaded, it is instantiated and the static {} code block is called. Only one instance of this class can exist per ClassLoader, and depending on the ClassLoader you are using, it may decide to check if any parent ClassLoader has already loaded the class.

Related Problems and Solutions