Item 53: Prefer interfaces to reflection

1.  Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods, and fields of the class represented by the Class instance. These objects provide programmatic access to the class’s member names, field types, method signatures, and so on. You can construct instances, invoke methods, and access fields of the underlying class by invoking methods on the Constructor, Method, and Field instances.

 

2.  Reflection allows one class to use another, even if the latter class did not exist when the former was compiled. This power, however, comes at a price:

    1) You lose all the benefits of compile-time type checking, including exception checking.

    2) The code required to perform reflective access is clumsy and verbose.

    3) Performance suffers.

 

3.  As a rule, objects should not be accessed reflectively in normal applications at runtime. There are a few sophisticated applications that require reflection. Examples include class browsers, object inspectors, code analysis tools, and interpretive embedded systems. Reflection is also appropriate for use in remote procedure call (RPC) systems to eliminate the need for stub compilers.

 

4.  For many programs that must use a class that is unavailable at compile time, there exists at compile time an appropriate interface or superclass by which to refer to the class. If this is the case, you can create instances reflectively and access them normally via their interface or superclass. If the appropriate constructor has no parameters, then you don’t even need to use java.lang.reflect; The Class.newInstance method provides the required functionality.

 

5.  If you are writing a program that has to work with classes unknown at compile time, you should, if at all possible, use reflection only to instantiate objects, and access the objects using some interface or superclass that is known at compile time.

 

你可能感兴趣的:(reflection,interfaces)