"Reflection", what's the point?

Discussions

General J2EE: "Reflection", what's the point?

  1. "Reflection", what's the point? (11 messages)

    Does anyone out there have a a good example of the use of "Reflection"? I have never thought that it adds any value and is just an amusing gimmick.

    Anyone?

    Threaded Messages (11)

  2. "Reflection", what's the point?[ Go to top ]

    Many IDEs and debuggers use reflection so they can put up those little property panes.
    Also very useful in dynamic proxies, JBoss for instance uses it everywhere.
  3. For example, you've got a hot-deployment requirement where you need to be able to use whatever class file dropped into a certain directory.
    <p>
    You must use a class loader, which is fine, but you don't know how to use the loaded class (e.g. instantiate it, invoke methods on it, etc.), which leads you to using reflection:<br>
    - find out what methods/attributes the class has<br>
    - get your hands on the implemented methods/attributes using the reflection API's classes and methods.<br>
  4. Another reason for using reflection is to invoke non-default constructors or static methods on an implementation-replacable object, since it is not possible to specify these on an interface.

    Persistence mapping engines are also classic candidates for use of reflection.

    Colin.
  5. In addition to what is stated it is used a lot in configuration. For example, there are configuration files written in xml (i.e. struts, log4j, weblogic, etc...) they describe things such as mappings for requests for services, application deployements, etc...
     
    They all parse these files and through the use of reflection they are able to located and use the appropriate resources.

    <sniplet source="STRUTS ACTION SERVLET (creating a action)">
     if (debug >= 1)
      log(" Creating new Action instance");
      /* Loads a class by reflection */
      Class clazz = Class.forName(actionClass);
      actionInstance = (Action) clazz.newInstance();
      actionInstance.setServlet(this);
      actions.put(actionClass, actionInstance);
    </sniplet>

    So it allows for powerful declaration of application properties in plain text files.
  6. "Reflection", what's the point?[ Go to top ]

    http://java.sun.com/j2se/1.4/docs/guide/reflection/

    Some useful information.
  7. best use...[ Go to top ]

    While it is very useful for tool vendors, how often are you writing an EJB container or IDE?

    Something that's useful that you may actually have to do is for getting/setting arbitrary properties at runtime.

    Say that you are going to fill up a value object (or Data Transfer Object) from your servlet request. Also say that you are not using Hashtable value objects, but instead JavaBeans type ones (i.e. gets/sets). You can loop through your list of request attributes, and lookup up methods based on them on your Value object class and then call them:

    Iterator iterator = getServletRequestParams();

    Class paramClasses[] = new Class[1];
    paramClasses[0] = String.class;

    String params[] = new String[1];

    while (iterator.hasNext())
    {
        String property = iterator.next();
        // set plus upper-cased property name
        String methodName = "set" + property.substring(0,1).toUpperCase() + property.substring(1);

        Method method = ValueObjectClass.class.getMethod(methodName,paramClasses);
        params[0] = request.getParameter(property);
        method.invoke(myValueObject,params);
    }

    So, you can get the benefit of using Hashtable value objects (i.e. simple code that sets whatever property you get), but the benefit of data structurs and types that you get from a JavaBean value object.
  8. best use...[ Go to top ]

    Thanks Dave. But I still don't think that is a good reason.

    I think relying on reflection makes no sense. If I have a class with a getName() method, I KNOW this. And I will call the getName() method. Are you suggesting that we write code that calls up arbitrary class names and arbitray method names and hope that we have a match? Of course not. We write Java classes to interact with each other by calling each others methods. Why place class names in an XML file and call them with reflection? Why not just write the Java code and compile it?

    No matter how fast the JDK is today, Reflection results in slower code.

    Thanks again Dave.
  9. best use...[ Go to top ]

    Not trying to defend Dave, but what he is getting at is that you don't know what class your going to be calling at compile time. If this is unknown then you need to dynamically load the class from a string input, client or config file, and once you have the class you again need to use reflection to instantiate it and invoke its methods.

    I wouldn't recommend its use in everyday code because your gut feeling is right, it's expensive. The classloader for the class needs to do a lookup delegating to its parent classloader all the way to the top system classloader and then back down. That's why classes that are first in the classpath are loaded and redundant ones are not. Part of the reason for this is because of the security concerns to prevent malicious from being added to the jvm after it's started. Typically in a production system this would be done with a caching mechanism to speed things up after the initial load.

    As mentioned frameworks like struts use it to allow the easy integration of the framework with your business domain objects. App servers use it to allow hot deployment, swapping classes in the class path with new one and flushing any cache.

    Are there any alternatives sure, just use a factory. And a large switch statement!
  10. best use...[ Go to top ]

    Yes, you may indeed know all the classes you are dealing with at runtime, and as such, it would be silly to use reflection. But, like many parts of the Java spec, it's there if you need it. If you have a lot of configuration, or you need to marshall free-form data (like properties or XML) into a strict Java object, reflection is the way to go.

    Also, it can be very useful for implementing custom tags (which I know you are also down on :).

    It is just a tool, and as such can be abused because it's "neat" (much like XML, EJB, J2EE, taglib, etc.)

    Dave
  11. It's a good way to generate dynamic content in a jsp page. <br>
    Suppose you have a jsp in wich you want to use some beans (beans that generate dynamic html for example), but depending of a condition (like the value of some property of another bean) you may need to instantiate different beans.<br>
    In this case you can write a "if ... else" very complex, non-flexible and non-dynamic structure, or better you can store this combinations in a relational database in a table like this (condition_value|bean class_name|bean constructor_parameters).<br>
    In this way using reflection you can instantiate any bean you need, by accessing to this table and searching for the controls you need.<br>
    If you need you can add new condition values or new beans for a condition value.<br>
    Peace.
  12. You use Reflection when you dont know the name of Class which you want to use.

    The best example of its use where i can think of is in tools like Servlet Container / EJB Container.

    Consider you have written a Servlet, say DummyServlet.java as follows.

    class DummyServlet extends HttpServlet
    {
       public void service(HttpServletRequest req,
                             HttpServletRequest resp )
       {
           //body of servlet
       }
    }

    Now, when a request comes to this Servlet, the Servlet Container has to instantiate this Class and invoke service method in that object.

    Now, the question is: How does your Servlet-Container instantiate your Class and call the service method??
    Can u imagine the container Code implementing this behaviour??

    In normal scenario, when you are writing a Java app, you know what Classes you use, so if DummyServlet was part of your application, you would call service method using following code:

    DummyServlet dummy = new DummyServlet();
    dummy.service(req,resp);

    As you can see, as you knew the name of Class you are using before-hand, you were able to directly instantiate the Class and call whatever method in the Class u wished.

    But, How would a Servlet-Container call the method on your Class...because it doesnt know the Classes which it would use ...i.e you will in future write a Class by name, "DummyServlet" and it should instantiate it and call method.

    It cannot have a Code like below i.e
    ( DummyServlet dummy = new DummyServlet();
    dummy.service(req,resp); )

    because the "DummyServlet.class" was not present, when the Container was written!!!

    So, how could a Servlet-Container handle this ?? The best soln to this can be to use Java Reflection

    and the Servlet-Container code to do that would be:-

    // Load the Class using string registered in web.xml
    Class c = Class.forName("com.dummy.DummyServlet");

    // get reference to "service" method
    Method method = c.getMethod("service", types);

    // instantiate the Class
    Object obj = c.newInstance();

    // invoke the service method passing Object and Parameters
    method.invoke(obj, params);

    where types is an array of method Parameter datatypes
    and params is array of method parameter Values with which u want to invoke the method with..

    Does it convince you about uses of Reflection??

    Get back on your view on this!!