路径:The Reflection API

原文: https://docs.oracle.com/javase/tutorial/reflect/index.html

反思的用途

反射通常由程序使用,这些程序需要能够检查或修改在 Java 虚拟机中运行的应用程序的运行时行为。这是一个相对高级的功能,只有那些掌握了语言基础知识的开发人员才能使用。考虑到这一点,反射是一种强大的技术,可以使应用程序执行本来不可能的操作。

Extensibility Features

An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.

Class Browsers and Visual Development Environments

A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.

Debuggers and Test Tools

Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

反思的缺点

反思是强大的,但不应随意使用。如果可以在不使用反射的情况下执行操作,则优选避免使用它。通过反射访问代码时,应牢记以下问题。

Performance Overhead

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Security Restrictions

Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

Exposure of Internals

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

小道教训

此跟踪包含用于访问和操作类,字段,方法和构造器的反射的常见用法。每课包含代码示例,提示和疑难解答信息。

trail icon Classes

This lesson shows the various ways to obtain a Class object and use it to examine properties of a class, including its declaration and contents.

trail icon Members

This lesson describes how to use the Reflection APIs to find the fields, methods, and constructors of a class. Examples are provided for setting and getting field values, invoking methods, and creating new instances of objects using specific constructors.

trail icon Arrays and Enumerated Types

This lesson introduces two special types of classes: arrays, which are generated at runtime, and enum types, which define unique named object instances. Sample code shows how to retrieve the component type for an array and how to set and get fields with array or enum types.


Note:

此跟踪中的示例旨在用于试验 Reflection API。因此,异常的处理与生产代码中使用的不同。特别是,在生产代码中,建议不要转储用户可见的堆栈跟踪。