Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - Difference between Class class and *.class files?

Tags:

There's something I don't understand between *.class files and Class class API. Let's me explain :

I have a file A.java representing a java class :

public class A { ... }

Class<?> clazz = A.class;

When I compile A.java, I get a A.class file (the byte code).

Is there any relation between the A.class file (bytecode) and clazz which represents the instance class (A.class) ? Are they the same thing ?

Thank you

like image 401
AntonBoarf Avatar asked May 17 '18 12:05

AntonBoarf


People also ask

Are there any differences between * .java file and * .class file?

A . java file contains your Java source code while a . class file contains the Java bytecode produced by the Java compiler.

What is the difference between class and file?

File is a file on the filesystem. Class is a Java class. Activity is a specific java class commonly used in Android. Save this answer.

What is the purpose of a .class file?

This file is what the Java Virtual Machine (JVM) interprets and converts into machine code. The class file is used by the JVM and not meant for your specific operating system. Every time you run a Java program, the Java compiler creates a . class file from the Java source code file.

Is Java file and Java class same?

A Java class file is a file containing Java bytecode and having . class extension that can be executed by JVM. A Java class file is created by a Java compiler from . java files as a result of successful compilation.


2 Answers

*.class files are files on the disk, A.class is a class object in the memory.

like image 184
xingbin Avatar answered Oct 02 '22 11:10

xingbin


Class<?> clazz = A.class;

is equivalent to

Class<?> clazz = Class.forName("A");

except that for the class literal, A.class, the compiler will check that A is available and accessible at compile-time, so its availability will be mandatory at runtime. Therefore, you don’t need to catch checked exceptions.

If A is not abstract and has a default constructor, you would get the same via

Class<?> clazz = new A().getClass();

Of course, all these constructs depend on the availability of a class definition for A at runtime, which is typically delivered in a class file name A.class, but the fact that one of these source code constructs looks similar to the file name has no relevance.

Note that for nested classes, the source code representation and the file name will differ, e.g. when using Map.Entry.class to refer to the nested type java.util.Map.Entry, the class file’s name will be Map$Entry.class. You could also add an import statement for this class and refer to it via Entry.class, showing that this construct is subject to the standard source code name resolution rules and not connected to the file name of the compiled class.

like image 23
Holger Avatar answered Oct 02 '22 11:10

Holger