开发者

Please confirm what .class does in java [duplicate]

开发者 https://www.devze.com 2023-03-25 11:56 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: In Java, what does a reference to Class.class do?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

In Java, what does a reference to Class.class do?

Firstly apologies for asking this question here. I know it's a simple question and can probably be answered quite quickly and easily. However searching for Java .class is such a loaded search term it brings up nothing useful.

Having said that, I just start开发者_运维百科ed learning Java and I just came across something like this:

Intent i = new Intent(this, ReminderManageActivity.class);

I am not sure, but I think ReminderManageActivity.class is an attribute that gives a string of the name of the class? Is that correct?


I know it sounds stupid, but class is a Class object that represent the Class.

If you want to instantiate / use some class, and you want to get this class as parametr, you can't just write Intent i = new Intent(this, ReminderManageActivity); since ReminderManageActivity is not an object.


In Java, given an object, an instance of a class, you can get the class name by coding the following:

Class clazz = obj.getClass();
String clazzName = clazz.getName();

Sometimes you want you want to create a Class object for a given class. In this case you can do so by writing code similar to the following example:

Class clazz = MyClass.class;

source


If you just started learning java than you will see more about this when you will study Type Information or RTTI(Runtime Type Information)

ReminderManageActivity.class 

is called a class literal and it produces a reference to the Class object, which contains information about the class in question.
It is similar to the static method :

Class.forName("ReminderManageActivity");


It is an instance of java.lang.Class which is part of Java Refleciton API. You can get more informaiton about the API here


Because everything in Java is an object, so even classes can be represented by objects.

ReminderManageActivity.class returns a Class object representing the ReminderManageActivity class.

A Class object contains information of a class, such as class' name, class' method, class's variables etc. You can look at the class API for more information: http://download.oracle.com/javase/6/docs/api/java/lang/Class.html

0

精彩评论

暂无评论...
验证码 换一张
取 消