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. CentOS6.5菜鸟之旅:关于搜索的shell命令

    一.locate命令 用于模糊搜索文件(目录)的绝对路径. 示例1: // 凡是绝对路径当中含jdk字符串的文件(目录)均被搜索出来 fsjohnhuang@fsjohnhuang~# locate ...

  2. Weblogic魔法堂:AdminServer.lok被锁导致启动、关闭域失败

    一.判断AdminServer.lok被其进程锁死 >weblogic.management.ManagementException: Unable to obtain lock on **** ...

  3. Web前端开发十日谈

    =========================================================================== 原文章: http://kb.cnblogs.c ...

  4. Linux - Ubuntu下JDK配置

    系统版本: ubuntu 14.04 x64JDK版本: jdk-8u60-linux-x64 1.查看系统位数,输入以下命令即可 getconf LONG_BIT 2.下载对应的JDK文件,我这里下 ...

  5. 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件

    [源码下载] 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件 作者:webabcd 介绍重新想象 Windows 8 Store ...

  6. MySQL的字符集

    MySQL的字符集支持(Character Set Support)有两个方面:字符集(Character set)和排序方式(Collation). 字符(Character)是指人类语言中最小的表 ...

  7. linux下基本命令总结

    基本linux命令的使用方法及实例,总结一些常用的命令:  一.创建文件和目录命令:mkdir touch(vim用得较多) 1)mdkir创建一个目录,创建多目录格式 mkdir –p a/{a,b ...

  8. 泛函编程(20)-泛函库设计-Further Into Parallelism

    上两节我们建了一个并行运算组件库,实现了一些基本的并行运算功能.到现在这个阶段,编写并行运算函数已经可以和数学代数解题相近了:我们了解了问题需求,然后从类型匹配入手逐步产生题解.下面我们再多做几个练习 ...

  9. Mybatis Physical Pagination

    1. Requirements: when we use the sql like "select * from targetTable", we get all records ...

  10. 非线性数据拟合-nls

    code{white-space: pre;} pre:not([class]) { background-color: white; }if (window.hljs && docu ...