zoukankan      html  css  js  c++  java
  • Effective Java 53 Prefer interfaces to reflection

    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.  

  • 相关阅读:
    P2176 [USACO14FEB]路障Roadblock
    洛谷 P1187 3D模型
    洛谷 P2777 [AHOI2016初中组]自行车比赛
    洛谷P2896 [USACO08FEB]一起吃饭Eating Together
    洛谷P2983 [USACO10FEB]购买巧克力Chocolate Buying
    洛谷 P2858 [USACO06FEB]奶牛零食Treats for the Cows
    Restaurant
    OR in Matrix
    poj 3321Apple Tree
    Codeforces Round #204 (Div. 2) C. Jeff and Rounding
  • 原文地址:https://www.cnblogs.com/haokaibo/p/prefer-interfaces-to-reflection.html
Copyright © 2011-2022 走看看