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. [编辑器]走上atom之路1

    祝大家新年快乐 我就是来卖个萌,逃- 正文 我最开始用atom是因为它看起来比较酷,我工作中主力还是使用pycharm,毕竟atom只是一个编辑器.我一 般只是用atom来写Markdown的文件.随 ...

  2. [mysql]增加用户 授权 远程登录

    mysql创建用户和授权 1.创建用户: (注意:下面的指令,请在root用户下输入) CREATE USER "用户名" IDENTIFIED BY "密码" ...

  3. 第一次接触终极事务处理——Hekaton

    在这篇文章里,我想给出如何与终极事务处理(Extreme Transaction Processing (XTP) )的第一次接触,即大家熟知的Hakaton.如果你想对XTP有个很好的概况认识,我推 ...

  4. 高级四则运算器—结对项目总结(193 &105)

    高级四则运算器—结对项目总结 为了将感想与项目经验体会分割一下,特在此新开一篇博文. 界面设计 啥都不说,先上图震慑一下... 上面的三个界面是我们本次结对项目的主界面,恩,我也觉得挺漂亮的!你问我界 ...

  5. IntelliTrace简介

    解决无法复现bug所使用的策略是在遇到bug时捕获尽可能多的信息,在使用IntelliTrace进行调试时可以充分利用这些信息.最令人称道的一个功能在于bug本身可以自动修复. 打开IntelliTr ...

  6. 【Win10】让 AppBarButton 支持更复杂的 Icon 内容

    最近有一个需求,需要制作这么一个 AppBarButton: 这个 AppBarButton 的 Icon 是一个评论框图标里面再显示评论数(大于 99 条则显示 99+).其中评论数是通过数据绑定得 ...

  7. MVC。Action方法,常用的返回类型有几种?

    常用的: 1,string,直接返回响应报文字符串 public ActionResult test(){return "哈哈";}2.ViewResult,ActionResul ...

  8. ACM训练场

    http://acm.nyist.net/JudgeOnline/problemset.php http://blog.csdn.net/SJF0115/article/category/910592 ...

  9. MySQL联接操作

    在MySQL中,联接是一种对表的引用, 多表联接类型: 1.笛卡尔积(交叉联接):在MySQL中为CROSS JOIN或省略JOIN,如: select * from course, teachcou ...

  10. Error generating Swagger server (Python Flask) from Swagger editor

    1down votefavorite   http://stackoverflow.com/questions/36416679/error-generating-swagger-server-pyt ...