what is the Class object (java.lang.Class)?
Nothing gets typecasted to Class
. Every Object
in Java belongs to a certain class
. That's why the Object
class, which is inherited by all other classes, defines the getClass()
method.
getClass()
, or the class-literal - Foo.class
return a Class
object, which contains some metadata about the class:
- name
- package
- methods
- fields
- constructors
- annotations
and some useful methods like casting and various checks (isAbstract()
, isPrimitive()
, etc). the javadoc shows exactly what information you can obtain about a class.
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the @Processable
annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class
instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
Note also that Class
object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
To summarize - each object in java has (belongs to) a class, and has a respective Class
object, which contains metadata about it, that is accessible at runtime.
Is class an object in JAVA?
In simple terms, think of a Class as a layout of a building and the Object as the building itself. With one layout you can build multiple buildings but each different from one and another. If you've a data member in your Class where you point to a different Class, they don't exist until you create a instance of your class.
So no Class it not an object by itself. But every Java object has an instance of the java.lang.Class
describing it. Such instances are objects though.
Determine if java.lang.Class object represents a class
I think it's a matter of elimination:
if (!c.isEnum() && !c.isInterface() && !c.isArray() && !c.isAnnotation() && !c.isPrimitive()) {
// It's a class
}
...which isn't very satisfying, as you have to revisit that definition when new features are added to Java (like enums, annotations, ...).
Are Java classes considered to be objects themselves?
Classes themselves are not objects in the sense that there is no runtime object that is directly used in the execution of a class. Other objects exist, however they are representations of the class and changes forced onto them in memory will not change the execution of that class's bytecode. However, every class has a Class
object associated with it that allows for interaction with that class, its instances, and members via reflection.
This class is actually generic in that FooClass.class is actually java.lang.Class<FooClass>
, which helps out with generics as passing a Class object in can resolve generic return types and constraints at runtime.
What does .class mean in Java?
When you write .class
after a class name, it references the class literal -java.lang.Class
object that represents information about a given class.
For example, if your class is Print
, then Print.class
is an object that represents the class Print
on runtime. It is the same object that is returned by the getClass()
method of any (direct) instance of Print
.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
How is it possible that java.lang.Object is implemented in Java?
You can implement java.lang.Object
in Java and the actual class you’re using has been indeed created from the Object.java
file that ships with the JDK.
The Java® Language Specification says in Chapter 8. Classes:
Each class except
Object
is an extension of (that is, a subclass of) a single existing class (§8.1.4) and may implement interfaces (§8.1.5).
So the absence of supertypes for Object
is fixed in the language.
You can use the source code of your experiment and try to add an extends
or implements
clause and see that the compiler will reject it.
When you compile the class java.lang.Object
, the resulting class file will be the only one that has no supertype. See The Java® Virtual Machine Specification, §4.1., The ClassFile Structure:
- super_class
For a class, the value of the
super_class
item either must be zero or must be a valid index into theconstant_pool
table. If the value of thesuper_class
item is nonzero, theconstant_pool
entry at that index must be aCONSTANT_Class_info
structure representing the direct superclass of the class defined by thisclass
file. Neither the direct superclass nor any of its superclasses may have theACC_FINAL
flag set in theaccess_flags
item of itsClassFile
structure.If the value of the
super_class
item is zero, then thisclass
file must represent the classObject
, the only class or interface without a direct superclass.For an interface, the value of the
super_class
item must always be a valid index into theconstant_pool
table. Theconstant_pool
entry at that index must be aCONSTANT_Class_info
structure representing the classObject
.
So even interfaces have an entry for the superclass in the class file (pointing to Object
) and the class file for java.lang.Object
is the only one with a zero entry for the super class.
When you try to load your version of the Object
class at runtime, you stumble across the fact that you can’t load classes of the java.lang
package (or any class whose qualified name starts with java.
) through the class path in general.
Prior to Java 9, you would have to set up the bootstrap class path to include your version. Starting with Java 9, the class java.lang.Object
must belong to the java.base
module, which is loaded in an implementation specific manner. You’d have to use the --patch-module
option to inject your own version.
But you have to be careful with what you write into your own version. There are a lot of expectations by other classes and the environment and not meeting them can break it (badly).
JLS, §4.3.2. The Class Object lists the expected methods and links to other chapters that define special language semantics for some of them.
What is the difference between the class Class in the Java API and the class keyword?
In programming, reflection is the ability of a program to modify its own structure and behavior at runtime through analysis of runtime details, such as the actual implementing class of an object instance. The Class
class is a part of the Java API for the purposes of reflection. Whereas the class
keyword is a structure of the Java language marking the definition of a new class, the Class
class is used to type variables and parameters as classes themselves. It's a way for the program to use class definitions themselves as objects to program around (you can programmatically enumerate over the class' public methods, for example).
Additionally, any instance o
of type Object
(that is, any object in Java at all) inherits the getClass
instance method. This yields the actual runtime class of the object, irrespective of the compile-time code-stated class of the variable the object is stored in. For example, for some defined class X
:
Object o = new X();
Class<?> type = o.getClass();
type
will now be a reference to the X
class itself, which matches the Class<?>
generic description because the X
class is in fact an instance of type Class<X>
.
Every defined class also has one static variable called class
referring back to the class itself. Calling getClass
on an instance of class X will return the same Class<X>
instance as that class' class
static variable:
("some string").getClass() == String.class
It is worth noting that the primitive types all have a static class
variable as well even though they are not Objects. It is also worth noting that a primitive type's class
is not the same as the class
of its wrapper class:
int.class != Integer.class
Related Topics
How to Display a Svg Byte Array as an Image in a Jasperreport
Easy Way of Running the Same Junit Test Over and Over
Java:Parse Java Source Code, Extract Methods
Run Exe Which Is Packaged Inside Jar File
In Java, When Does an Object Become Unreachable
How to Set Icon to a Jlabel from an Image from a Folder
Persistence Unit as Resource_Local or Jta
How to Create an Object of an Interface
Detect and Extract Url from a String
Selenium Many Logs (How to Remove)
Get Maven Artifact Version at Runtime
Format File Size as Mb, Gb, etc
Order of Loading Jar Files from Lib Directory
Preserving Parameter/Argument Names in Compiled Java Classes