what is the Class object (java.lang.Class)?
Asked Answered
E

7

92

The Java documentation for Class says:

Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

What are these Class objects? Are they the same as objects instantiated from a class by calling new?

Also, for example object.getClass().getName() how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?

Esemplastic answered 15/12, 2010 at 18:10 Comment(0)
S
104

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.

Spend answered 15/12, 2010 at 18:13 Comment(8)
And it's fun to think about this further. The Class class inherits from Object itself. Class.class returns a Class object that represents the Class class. You can reflect on reflection. MY HEAD ASPLODE.Enrica
@Enrica Haven't use Ruby much, huh? :-)Spondee
@pst: I have. It makes me want to hurt people. Any language/framework with this many methods on its root type deserves to be buried. It has PHP-style tack-random-crap-onto-the-API-without-any-forethought syndrome. Cue the flames...Enrica
Class c1 = Car.class; What is this "class" ? is it a public variable which exists in every class ?Kimberleykimberli
In a way, yes. In fact, it's a "class literal" - that's the way you refer to the Class object by name.Spend
@Spend shouldn't it be the object class which gets inherited by all other class?Sonorous
@Enrica Your comment semantically satiated the word 'class' for me.Renault
@Spend If I create 5 (objects) instances of a class does that mean that each of them will receive a copy of the .class object for that class or there will be only 1 .class object whose reference will be given to each of the 5 objects? That is important for multi-threading and the locking mechanisms there. If you do synchronized methodA() and static synchronized methodB() the later will be locked to the .class and if I have 5 obj. of the class methods A and B belong to then how many .class objects are generated becomes relevant. Sorry for being a bit late to the party :)Hankhanke
N
49

A Class object is sort of a meta object describing the class of an object. It is used mostly with the reflection capabilities of Java. You can think of it like a "blueprint" of the actual class. E.g. you have a class Car like this:

public class Car {
    public String brand;
}

You can then construct a Class object which describes your "Car" class.

Class myCarClass = Class.forName("Car");

Now you can do all sorts of querying on your Car class on that Class object:

myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field

and so on. Every java object has a method getClass() which returns the Class object describing the Class of the Java object. So you could do something like:

Car myCar = new Car();
Class myCarClass  = myCar.getClass();

This also works for objects you don't know, e.g objects you get from the outside:

public void tellMeWhatThisObjectsClassIs(Object obj) {
    System.out.println(obj.getClass().getName());
}

You could feed this method any java object and it will print the actual class of the object you have given to it.

When working with Java, most of the time you don't need to worry about Class objects. They have some handy use cases though. E.g. they allow you to programmatically instanciate objects of a certain class, which is used often for object serialization and deserialization (e.g. converting Java Objects back and forth to/from XML or JSON).

Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance();  // is roughly equivalent to = new Car();

You could also use it to find out all declared fields or methods of your class etc, which is very useful in certain cases. So e.g. if your method gets handed an unknown object and you need to know more about it, like if it imlements some interface etc, the Class class is your friend here.

So long story short, the Class, Field, Method, etc. classes which are in the java.lang.reflect package allow you to analyze your defined classes, methods, fields, create new instances of them, call methods all kinds of other stuff and they allow you to do this dynamically at runtime.

Notepaper answered 15/12, 2010 at 18:25 Comment(2)
Class c1 = Car.class; What is this "class" ? is it a public variable which exists in every class ?Kimberleykimberli
It's basically syntactic sugar. It is something the compiler evaluates to something that loads the class object with the given name. Roughly equivalent to Class.forName("fully qualified class name") but the class is checked to exist at compile time while Class.forName() is executed at runtime.Furuncle
S
8

getClass() is a method that returns an object that is an instance of java.lang.Class... there is no casting involved. Casting would look like this:

Class<?> type = (Class<?>) object;
Suzette answered 15/12, 2010 at 18:16 Comment(0)
H
7

I would also like to add to ColinD 's answer that getClass will return the same object for instances of same type. This will print true:

    MyOtherClass foo = new MyOtherClass();
    MyOtherClass bar = new MyOtherClass();
    System.out.println(foo.getClass()==bar.getClass());

Note that it is not equals, I am using ==.

Hugely answered 2/5, 2015 at 9:24 Comment(0)
G
4

In order to fully understand the class object, let go back in and understand we get the class object in the first place. You see, every .java file you create, when you compile that .java file, the jvm will creates a .class file, this file contains all the information about the class, namely:

  1. Fully qualified name of the class
  2. Parent of class
  3. Method information
  4. Variable fields
  5. Constructor
  6. Modifier information
  7. Constant pool

The list you see above is what you typically see in a typical class. Now, up to this point, your .java file and .class file exists on your hard-disk, when you actually need to use the class i.e. executing code in main() method, the jvm will use that .class file in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .class file into the method area, the jvm will use that information and a Class object that represents that class that exists in the heap memory area.

Here is the top level view,

.java --compile--> .class -->when you execute your script--> .class loads into method area --jvm creates class object from method area--> a class object is born

With a class object, you are obtain information such as class name, and method names, everything about the class.

Also to keep in mind, there shall only be one class object for every class you use in the script.

Hope this makes sense

Godwit answered 16/5, 2019 at 21:4 Comment(2)
good additional points. one remark on wording, I do not know subject that good to edit myself "the jvm will use that information and a Class object that represents that class that exists in the heap memory area." looks not correct, line later with --> looks more logical. Am I right here? please make consistent, thank you!Endorsement
@Brendon Cheung when you said 'a Class object that represents that class', it's a class, not the instance of that class, so I think we should modify the expression. Because only 'instances' go into heap memory, not their class.Finical
H
3

A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question

Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

Hanseatic answered 15/12, 2010 at 19:1 Comment(0)
T
1

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();//we don't know what object will be returned from this method

Tanguay answered 19/1, 2019 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.