Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection
- You lose all the benefits of compile-time type checking, including exception checking.
- The code required to perfrom reflective access is clumsy and verbose.
- 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.
- Class browers.
- Object inspectors.
- Code analysis tools.
- Interpretive embedded systems.
- Remote procedure call(RPC) systems to eliminate the need of stub compilers.
- Use of reflection is to manage a class's dependencies on other classes, methods, or fields that may be absent at runtime.
- 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
- Objects should not be accessed reflectively in normal applications at runtime.
- 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的更多相关文章
- Effective Java 18 Prefer interfaces to abstract classes
Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...
- 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 ...
- 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 ...
- Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...
- 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 ...
- 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 ...
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- Effective Java 25 Prefer lists to arrays
Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...
- 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 ...
随机推荐
- SQL语句技巧之去除重复行
去除表中重复行数据,可能大家立马就想到的是用DISINTCT关键字,但DISINTCT只能是去除表中所有列都相同的行,若碰到需要去除表中多个字段重复的行(即:部份相同,部份不相同),那么该如何做呢?我 ...
- Weblogic魔法堂:AdminServer.lok被锁导致启动、关闭域失败
一.判断AdminServer.lok被其进程锁死 >weblogic.management.ManagementException: Unable to obtain lock on **** ...
- struts2重点——ValueStack和OGNL
一.值栈(ValueStack) 1.实现类:OGNLValueStack 2.对象栈:CompoundRoot(针对的是类级别的) (1)继承自 ArrayList —— 先进后出 (2)提供了栈的 ...
- Sprint 3计划
一.计划目标: 1.完成基本的首页面的信息查询功能 2.学生家教用户注册和登录,将信息存储到数据库 3.完成家教的资格评定设定和个人教学内容备份信息 二.燃尽图 三.项目具体工作细则 待明天工作会议分 ...
- undefined reference to `omp_get_max_threads'
原因是缺少 libgomp/openmp 库的链接 配置和解决方法参考: http://www.code-by.org/viewtopic.php?f=54&t=163
- Tempdb的并发阻塞
9.3 Tempdb的并发阻塞 在介绍Tempdb的并发问题前,先介绍几个比较特殊的数据页. PFS(Page Free Space),用于标识数据页空间的使用情况,以字节标识,可以表示数据页使用百分 ...
- 字符串 --- KMP Eentend-Kmp 自动机 trie图 trie树 后缀树 后缀数组
涉及到字符串的问题,无外乎这样一些算法和数据结构:自动机 KMP算法 Extend-KMP 后缀树 后缀数组 trie树 trie图及其应用.当然这些都是比较高级的数据结构和算法,而这里面最常用和最熟 ...
- dp --- Codeforces 245H :Queries for Number of Palindromes
Queries for Number of Palindromes Problem's Link: http://codeforces.com/problemset/problem/245/H M ...
- ASP.NET 取得 Uri 各项属性值
Uri uri = new Uri("http://www.yoercn.com/aboutus/idea.html");string Host = uri.Host; ...
- c#泛型方法返回null的问题
c#的泛型方法实现和java实现有点不同,在java中,所有的泛型方法运行时类型必须是引用类型,所以和非泛型一样可以返回null. 但是c#中有点不同,可以同时是值类型和引用类型,而值类型不能赋值nu ...