Question

I'm teaching myself to create classes that can be overridden externally, basically to simulate a framework where I provide only implementation for an interface. I notice that hadoop actually uses:

job.setMapperClass(FrameworkObject.class);

in a driver class to do this, is it a simple alteration to change this code below to do that?

//----- locked framwork interface...
public interface FrameworkInterface {
    public void PrintStuff();
}

//----- locked framwork factory class...
public class FrameworkFactory {

    public static void doStuff(FrameworkInterface fi){
        fi.PrintStuff();
    }
}

//------------ my code that hooks into a framework...
public class FrameworkObject implements FrameworkInterface {

    public FrameworkObject() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void PrintStuff() {
        System.out.println("the implemented method...");
    }
}

//------------ the framework driver I want to change 
public class FrameworkDriver {

    public static void main(String[] args){
        FrameworkFactory.doStuff(new FrameworkObject()); // explicit ref to object
    }
}
Was it helpful?

Solution

In all frameworks you require an entry point that configures mappings or component injection. In your example this is the FrameworkDriver. It's not possible to simply scan for implementations and load them dynamically. I would suggest one of two possible solutions.

1) You add a method to the FrameworkDriver that creates the FrameworkObject that is used in the creation of the framework (extending classes would need to override main as otherwise it it will create an instance of the original class and miss this extension). This allows other implementations of FrameworkDriver to override this and provide an alternative implementation.

2) Your driver reads a system property or file which contains the class name for the object or a factory thereof so you no longer need to code it in. Many dependency injection frameworks have used this approach, and some handle it automatically by generating the file from a build plugin or other source processor.

In general though you would probably be better off using a ready made system such as Guice.

OTHER TIPS

If you're looking for a built-in mechanism, than a custom Service Provider is probably your answer (available since Java 1.6).

This is my quick hack to solve the problem, it then takes any class that can be cast to the FrameworkInterface... Think this is what you meant ajwillia.ms?

public class FrameworkFactory {

public static void doStuff(Class<?> class1) throws Exception{
        FrameworkInterface fi = (FrameworkInterface) class1.newInstance();
        fi.PrintStuff();
}   
}

public class FrameworkDriver {

public static void main(String[] args) throws Exception{
    FrameworkFactory.doStuff(FrameworkObject.class);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top