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. JS魔法堂:IE5~9的Drag&Drop API

    一.前言     < HTML5魔法堂:全面理解Drag & Drop API>中提到从IE5开始已经支持DnD API,但IE5~9与HTML5的API有所不同,下面我们来了解一 ...

  2. C#开源资源项目

    一.AOP框架 Encase 是C#编写开发的为.NET平台提供的AOP框架.Encase 独特的提供了把方面(aspects)部署到运行时代码,而其它AOP框架依赖配置文件的方式.这种部署方面(as ...

  3. JdbcTemplate使用总结

    Spring JdbcTemplate 在数据库的操作中,每个业务方法都要得到连接,开启事务,提交事务,回滚,关闭连接等,我们可以把这些做成一个模版,这样,在业务代码中只需要关注业务逻辑即可. MyJ ...

  4. Chrome浏览器的Timing分析

    以W3C网站为例: Stalled是浏览器得到要发出这个请求的指令,到请求可以发出的等待时间,一般是代理协商.以及等待可复用的TCP连接释放的时间,不包括DNS查询.建立TCP连接等时间等. SSL( ...

  5. yii2.0用户登录,退出判断(摘录)

    文章来源:http://blog.sina.com.cn/s/blog_88a65c1b0101ix13.html 判断用户是否登录 在 Yii2.0 里面,判断用户是否已经登录,我们用下面的代码即可 ...

  6. PHP学习笔记:MySQL数据库的操纵

    Update语句 Update 表名 set 字段1=值1, 字段2=值2  where  条件 练习: 把用户名带  ‘小’的人的密码设置为123456@ 语句:UPDATE crm_user SE ...

  7. MySQL Plugin 'InnoDB' init function returned error一例

    早上上班后,测试说演示环境挂了,维护上去看了下,启动报错了: XXXXXX08:30:47 mysqld_safe Starting mysqld daemon with databases from ...

  8. galera cluster DDL节点间状态不一致的问题

    近期某个系统中的galera cluseter环境发生A DDL操作后,B节点未同步的情况,同时B节点的errorlog中有如下警告信息: 2016-07-23 17:31:32 18920 [War ...

  9. java微信开发(wechat4j)——access_token中控服务器实现

    access_token是与微信服务器交互过程中的一个凭证,每次客户服务器主动与微信服务器通信都需要带上access_token以确认自己的身份.wechat4j内部封装了对access_token的 ...

  10. 【python】获取高德地图省市区县列表

    项目中需要用省市区来进行检索,原想高德地图肯定会有API来获得这些数据,结果没有找到,有一个接口好像可以用,但是会附带大量的边界坐标点. 所以就不如自己把高德的省市区列表扒下来,自己写接口来完成这个功 ...