Using Reflection

Reflection is a feature in the Java programming language. It supports dynamic retrieval of information about classes and data structures by name, and allows for their manipulation within an executing Java program. This is handy for obtaining class information. But it is also possible to use reflection to create new objects and invoke a method of a specific name. This is what the ReflectionUtil class is used for in INTViewer.

The Java reflection classes are found in java.lang.reflect

The ReflectionUtil class is found in com.interactive.intviewerapi.util

Overloaded Methods

newInstance(String fullyQualifiedClassName)
newInstance(Class<?> klass)
newInstance(String fullyQualifiedClassName, Class[] paramKlasses, Object[] params)
newInstance(Class<?> klass, Class<?>[] paramKlasses, Object[] params)

Exceptions

All methods in the ReflectionUtil class throw the following exceptions:

IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException

Example 1

Found in the AbstractLayerFactory class (createLayer method)

where m is an IMemento object and destWindow is an ILayeredWindow object

        ViewerLayer2D layer = null;
        int layerId = m.getInteger(ViewerLayer2D.ID, ViewerLayerFactory.getInstance().createUniqueLayerId());
        // get the class name for the layer to be restored from the session IMemento document
        String layerClassName = m.getString(ViewerLayer2D.CLASS);
        // store the class types for the parameter objects
        Class<?>[] classParameters = {destWindow.getClass().getSuperclass(), Integer.TYPE};
        // store the parameter objects
        Object[] parameters = {destWindow, layerId};
        // pass the parameter arrays to the "layerClassName" constructor
        layer = (ViewerLayer2D) ReflectionUtil.newInstance(layerClassName, classParameters, parameters);

The reflection allows all classes extending the AbstractLayerFactory to use the one createLayer method for session restore without the AbstractLayerFactory having to hard-code information about the subclasses.

Example 2

Found in the IData.Factory class

where dataM is an IMemento object

        String dataKlassName = null;
        try {
            // get the class name for the data to be restored from the IMemento document
            dataKlassName = dataM.getString(IData.DATA_CLASS);
            if (dataKlassName != null) {
                realData = (IData) ReflectionUtil.newInstance(dataKlassName);
            }
        } catch (Exception e) {
            throw new Exception("Failed to create data source for data class = " + dataKlassName + " : " + e.getMessage());
        }

To use the IData Factory:

where m is an IMemento object

              IData realData = IData.Factory.createNewInstance(m);