简体   繁体   English

在Java中,对Class.class的引用是做什么的?

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

I'm building a small Android application, but this is more of a Java question than an android question. 我正在构建一个小型的Android应用程序,但这更像是一个Java问题,而不是一个Android问题。 Looking through the tutorials there are lines that look like: 查看教程中的行看起来像:

startService(new Intent(this, MyService.class));

what exactly does the "MyService.class" field represent? “MyService.class”字段到底代表什么? Is that just a reference to the class for a template? 这仅仅是对模板类的引用吗?

Thanks. 谢谢。

Andy's answer is definitely correct, but I want to expand on the point a little. 安迪的答案肯定是正确的,但我想稍微扩展一点。

.class is a special syntax for obtaining an instance of a Class object. .class是获取Class对象实例的特殊语法。 It can be used when only the type is available and no instance of the related object is around. 当只有类型可用且没有相关对象的实例时,可以使用它。 It can be used with any concrete type name, including arrays and primitives. 它可以与任何具体类型名称一起使用,包括数组和基元。 For instance, int.class is valid. 例如, int.class是有效的。

This way (and other ways) to get a Class object are documented in the old Sun reflection API docs . 这种(和其他方式)获取Class对象的方法记录在旧的Sun反射API文档中

The special .class syntax often appears in idiomatic usage as a "type token" in generic code. 特殊的.class语法经常出现在惯用语中作为通用代码中的“类型标记”。 A class literal obtained with .class is called a type token when "passed among methods to communicate both compile-time and runtime type information" ( Joshua Bloch's Effective Java 2e , p. 142). 当“在传递编译时和运行时类型信息的方法之间传递”时,使用.class获得的类文字称为类型标记( Joshua Bloch的Effective Java 2e ,p.142)。

Yes, MyService.class returns a Class object that represents the class MyService. 是的, MyService.class返回一个表示MyService类的Class对象。 The Intent uses it to identify which Service or Activity you're intending to start. Intent使用它来标识您打算启动的服务或活动。

MyService.class允许您从类名中获取描述MyClass类的Class对象(而不是让类的实例请求object.getClass() )。

In JVM, when a class is loaded, an object of the type Class represents the loaded class in memory. 在JVM中,当加载类时,类型为Class的对象表示内存中加载的类。 com.abc.MyClass.class is a literal expression that represents the Class object for the class com.abc.MyClass . com.abc.MyClass.class是一个文字表达式,表示类com.abc.MyClassClass对象。

The same Class object can also be obtained by calling myClassReference.getClass() method if you have a reference to an object of the class. 如果您具有对类的对象的引用,则还可以通过调用myClassReference.getClass()方法来获取相同的Class对象。

The Class object can be used to find the information on the structure of the class, access fields, invoke methods and instantiate objects of the class using Java Reflection API. Class对象可用于查找有关类结构的信息,访问字段,调用方法以及使用Java Reflection API实例化类的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM