9

Possible Duplicate:
What is reflection, and why is it useful?

What is the exact use of reflection in Java? Can anyone demonstrate with an example? If there are any related concepts, please share.

Community
  • 1
  • 1
JAVA Beginner
  • 389
  • 3
  • 15

2 Answers2

11

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:

public Strategy prepare(String clazz, Properties config) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class<?> clazz = Class.forName(clazz);
    Strategy strategy = (Strategy) clazz.newInstance();
    strategy.initialise(config);
    return strategy;
}

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.

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.

private static CacheManager getRawInstance() {
    lock.lock();
    try {
        final Field field = CacheManager.class.getDeclaredField("singleton");
        field.setAccessible(true); // << -- ??
        return (CacheManager) field.get(CacheManager.class);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        lock.unlock();
    }
}

Here, the private field in ehcache is changed and accessed. This is downright bad coding.

Jaco Van Niekerk
  • 4,180
  • 2
  • 21
  • 48
  • 1
    Wait, Field.setAccessible(true) was used in production??? I'm guessing that was an interesting day when that gem was found. – Dan Jan 16 '13 at 07:22
  • Yes Dan, indeed... the lock also polished the gem a bit more (what happened to "synchronized"?). The issue was discovered when ehcache started misbehaving in other parts of the system (ignoring configuration, etc.) After factoring it out... it was left intact with a comment as a warning. It was a good lesson. It illustrates how dangerous reflection code can be. – Jaco Van Niekerk Jan 16 '13 at 07:42
1

TechExchange did a great job explaining reflection. Reflection seems to be a black sheep in Java. I always hear people saying that's its buggy and error prone, but I found it to be pretty stable and efficient when it's done right. I will say avoid using it and try an introspection library over writing native reflection code. Introspection the same thing as reflection, generally just a library built on an underlying reflection library. Spring and Apache-commons both have great tools, if you are working with beans.

Spring and Apache only target getters, unfortunately, I don't live in a bean world. Some of the objects I had to work with are Boolean 'is' methods and did found myself writing reflection code.

Anyway here is some simple reflection code that stores every public method with 0 arguments.

public void foo(final Class _class){
    List<Method> methods = new ArrayList<Method>(){{
        for( Method method : _class.getMethods() ) {

            if( Modifier.isPublic( method.getModifiers() ) 
                && method.getGenericParameterTypes().length == 0 ){

            add(method);
        }
    }};
}
Dan
  • 1,179
  • 2
  • 10
  • 18