what is Class Object(java.lang.class) in java?

 

 

JAVA documentation tells "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?

share | improve this question
 
 
up vote 19 down vote accepted

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 enums and interfaces also represent a Class object, 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.

share | improve this answer
 
11 
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. –  cdhowie Dec 15 '10 at 18:15
 
@cdhowie Haven't use Ruby much, huh? :-) –  user166390 Dec 15 '10 at 18:23
 
@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... –  cdhowie Dec 15 '10 at 18:26
 
Class c1 = Car.class; What is this "class" ? is it a public variable which exists in every class ? –  david blaine Apr 17 at 2:32
 
In a way, yes. In fact, it's a "class literal" - that's the way you refer to the Class object by name. –  Bozho Apr 17 at 8:41
No problem. We won't show you that ad again. Why didn't you like it?
Oops! I didn't mean to do this.

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 to XML and back, well mostly back).

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.

share | improve this answer
 
 
Class c1 = Car.class; What is this "class" ? is it a public variable which exists in every class ? –  david blaine Apr 17 at 2:32
1 
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. –  Jan Thomä Apr 17 at 12:12

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;
share | improve this answer
 
 

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.

share | improve this answer
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值