Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Reflection is a powerful construct which is often used by underlying libraries such as Guice and Hibernate to make life easier. It is often used where a class needs to be configured and then instantiated on the fly. For example:</p> <pre><code>public Strategy prepare(String clazz, Properties config) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class&lt;?&gt; clazz = Class.forName(clazz); Strategy strategy = (Strategy) clazz.newInstance(); strategy.initialise(config); return strategy; } </code></pre> <p>Here, the clazz parameter names the class to instantiate. It is assumed that the class will be a subclass of the Strategy class/interface. It is then also initiated with settings passed in through the config parameter. This allows for a highly configurable/dynamic environment.</p> <p>However, reflection quite often leads to very dangerous (and malicious) code and for that reason, reflection should be avoided, unless absolutely necessary. Also keep in mind, that reflection is slower than a direct call. Here's an actual example pulled from a production system of how NOT to use reflection.</p> <pre><code>private static CacheManager getRawInstance() { lock.lock(); try { final Field field = CacheManager.class.getDeclaredField("singleton"); field.setAccessible(true); // &lt;&lt; -- ?? return (CacheManager) field.get(CacheManager.class); } catch (Exception e) { logger.error(e.getMessage(), e); return null; } finally { lock.unlock(); } } </code></pre> <p>Here, the private field in ehcache is changed and accessed. This is downright bad coding. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload