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
A . java file contains your Java source code while a . class file contains the Java bytecode produced by the Java compiler.
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.
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.
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.
*.class files are files on the disk, A.class
is a class object in the memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With