Introduction
I'm Implementing Dependency Injection into my code.
I've gotten to a point where I have a properties file configured named config.properties. I also know how to reflect the property strings into an object.
The Problem
The problem is that when I do this reflection java says the type is going to be Class<?>
and I want it to be a generic type D
so I can reuse the code that's coupled with this class.
Where I'm At
Below is the code where D
is my generic object I want to cast to. ObjectImplementation
is the layer of abstraction (so every object that gets used on this class implements that interface). SalesRepbyID
is just the name of the container class. fileparser
is a different part of the dependency injection (ignore that for now). And finally, Parse is the method that constructs the instances I need to cast.
I've googled the title and searched through Stackoverflow results as well as external webpages. I think what I'm missing is called a Factory Pattern but I'm unsure of how to implement such a thing or if I'm even on the right track.
The Goal
The Goal here is to use the reflection and generic typing so that any Class that implements ObjectImplementation
can be constructed in this container class and the implementation to use can be changed through the properties file and NOT the code. Any silly things I'm doing with regard to naming conventions please let me know and thanks as always for your efforts.
public class SalesRepbyId<D extends ObjectImplementation> implements
DataParserImplementation<Map<String,D>> {
private FileParserImplementation<ArrayList<String[]>> FileParser;
public SalesRepbyId(FileParserImplementation<ArrayList<String[]>> FileParser){
this.FileParser = FileParser;
}
@Override
public Map<String, D> Parse() {
Properties prop = new Properties();
try {
prop.load(Data_Parser.class.getResourceAsStream("config.properties"));
} catch (IOException e) {
System.out.println(e + " error with config.properties I/O");
}
try {
Class<?> classToUse = Class.forName(prop.getProperty("ObjectImplementation"));
//construct classToUse instances here in the method many times with type D
Aucun commentaire:
Enregistrer un commentaire