Disadvantage of reflection

  1. You lose all the benefits of compile-time type checking, including exception checking.
  2. The code required to perfrom reflective access is clumsy and verbose.
  3. Peformance suffers.

When to use reflecition

Design time - Component-based application builider tools which load classes on demand and use reflection to find out what methods and constructors they support.

When at compile time an appropriate interface or super class by which to refer to the class(Item 52) which is unavailable at compile time.

  1. Class browers.
  2. Object inspectors.
  3. Code analysis tools.
  4. Interpretive embedded systems.
  5. Remote procedure call(RPC) systems to eliminate the need of stub compilers.
  6. Use of reflection is to manage a class's dependencies on other classes, methods, or fields that may be absent at runtime.
  7. Service provider framework(Item 1).

// Reflective instantiation with interface access

public static void main(String[] args) {

// Translate the class name into a Class object

Class<?> cl = null;

try {

cl = Class.forName(args[0]);

} catch(ClassNotFoundException e) {

System.err.println("Class not found.");

System.exit(1);

}

// Instantiate the class

Set<String> s = null;

try {

s = (Set<String>) cl.newInstance();

} catch(IllegalAccessException e) {

System.err.println("Class not accessible.");

System.exit(1);

} catch(InstantiationException e) {

System.err.println("Class not instantiable.");

System.exit(1);

}

// Exercise the set

s.addAll(Arrays.asList(args).subList(1, args.length));

System.out.println(s);

}

When not to use reflection

  1. Objects should not be accessed reflectively in normal applications at runtime.
  2. 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.

Summary

Reflection is a powerful facility that is required for certain sophisticated system programming tasks, but it has many disadvantages. 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.

Effective Java 53 Prefer interfaces to reflection的更多相关文章

  1. Effective Java 18 Prefer interfaces to abstract classes

    Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...

  2. Effective Java 69 Prefer concurrency utilities to wait and notify

    Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...

  3. Effective Java 19 Use interfaces only to define types

    Reason The constant interface pattern is a poor use of interfaces. That a class uses some constants ...

  4. Effective Java 35 Prefer annotations to naming patterns

    Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...

  5. Effective Java 49 Prefer primitive types to boxed primitives

    No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...

  6. Effective Java 68 Prefer executors and tasks to threads

    Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...

  7. Effective Java 20 Prefer class hierarchies to tagged classes

    Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...

  8. Effective Java 25 Prefer lists to arrays

    Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...

  9. Effective Java 46 Prefer for-each loops to traditional for loops

    Prior to release 1.5, this was the preferred idiom for iterating over a collection: // No longer the ...

随机推荐

  1. UWP开发入门(十六)——常见的内存泄漏的原因

    本篇借鉴了同事翔哥的劳动成果,在巨人的肩膀上把稿子又念了一遍. 内存泄漏的概念我这里就不说了,之前<UWP开发入门(十三)——用Diagnostic Tool检查内存泄漏>中提到过,即使有 ...

  2. C#设计模式——适配器模式(Adapter Pattern)

    一.概述在软件开发中,常常会想要复用一个已经存在的组件,但该组件的接口却与我们的需要不相符,这时我们可以创建一个适配器,在需复用的组件的接口和我们需要的接口间进行转换,从而能够正常的使用需复用的组件. ...

  3. Mysql –>EF edmx(model first)–> Sql server table

    一.mysql environment When we create an new database,first We need draw er diagram for somebody to sho ...

  4. sql server:compare data from two tables

    --Comparing data between two tables in SQL Server --Create two Tables-- CREATE TABLE TableA(ID Int, ...

  5. java设计模式--工厂模式

       所谓工厂,就是要造产品,比如一个小型砖瓦厂,只有一个窑,既能造砖又能造瓦,这种叫简单工厂模式.规模稍大一点呢,我多个窑,有的窑专门造砖,有的窑专门造瓦,想造别的,比如瓷砖,我再用个专门的窑,这种 ...

  6. MessageFormat格式化的一些问题

    如果格式化字符串中包含单引号,处理方法是用2个单引号进行转义,如果是数字,则需要加上格式: MessageFormat.format("(''{0}'',''{1}'',{2,number, ...

  7. Thumbnailator压缩图片

    Thumbnailator是一款不可多得的处理图片的第三方工具包,它写法简单到让人无法相信,Java本身也有处理图片压缩的方法,但是代码冗长到让人痛不欲生,在篇末会给出Java本身的实现方式,做下对比 ...

  8. 硬盘变成RAW的修复过程

    可能在不知道为什么的情况下,移动硬盘或者本地磁盘的每个分区变成了RAW格式.其在Win系统下的无损修复过程如下: 用“win”+“R”打开“运行”小窗口: 键入“CMD”: 键入命令“CHKDSK P ...

  9. Android破解之Lic文件加密程序(首例)

    我不会写Android,这是我第一个破解Android的例子,耗时接近一天,希望大神不要见笑! 本程序为商业软件,不便发布APK程序. 不要给我发消息,我不得回,有问题,直接回帖就可以了. 准备工作 ...

  10. CRM 2013 系统设置新功能一:界面自动保存 及 SDK 中 Xrm.Page.data.entity.save

    CRM 2013 界面会自动保存了..在系统设置中默认“是”,如果不需要可以调整. CRM实体记录在新建时会有出现“保存”按钮,非新建状态下,没有“保存”按钮只有“新建”按钮,系统将会自动为你保存最后 ...