Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming with Core JAVA - Reflection API [duplicate]

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.

like image 566
JAVA Beginner Avatar asked Jan 16 '13 06:01

JAVA Beginner


2 Answers

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.

like image 117
Jaco Van Niekerk Avatar answered Nov 15 '22 17:11

Jaco Van Niekerk


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);
        }
    }};
}
like image 42
Dan Avatar answered Nov 15 '22 17:11

Dan